From c35ed6570b7aedc355400b5c5105c0ce25c0adf0 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 5 Feb 2024 17:33:02 +0200 Subject: [PATCH] LibC: Implement endiannes and ip address functions --- libc/CMakeLists.txt | 1 + libc/arpa/inet.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 libc/arpa/inet.cpp diff --git a/libc/CMakeLists.txt b/libc/CMakeLists.txt index ae5461bb1d..8f3f867327 100644 --- a/libc/CMakeLists.txt +++ b/libc/CMakeLists.txt @@ -3,6 +3,7 @@ cmake_minimum_required(VERSION 3.26) project(libc CXX ASM) set(LIBC_SOURCES + arpa/inet.cpp assert.cpp ctype.cpp dirent.cpp diff --git a/libc/arpa/inet.cpp b/libc/arpa/inet.cpp new file mode 100644 index 0000000000..e81ef38566 --- /dev/null +++ b/libc/arpa/inet.cpp @@ -0,0 +1,52 @@ +#include + +#include +#include +#include + +uint32_t htonl(uint32_t hostlong) +{ + return BAN::host_to_network_endian(hostlong); +} + +uint16_t htons(uint16_t hostshort) +{ + return BAN::host_to_network_endian(hostshort); +} + +uint32_t ntohl(uint32_t netlong) +{ + return BAN::host_to_network_endian(netlong); +} + +uint16_t ntohs(uint16_t netshort) +{ + return BAN::host_to_network_endian(netshort); +} + +in_addr_t inet_addr(const char* cp) +{ + uint32_t a = 0, b = 0, c = 0, d = 0; + int ret = sscanf(cp, "%u.%u.%u.%u", &a, &b, &c, &d); + if (ret < 1 || ret > 4) + return (in_addr_t)(-1); + uint32_t result = 0; + result |= (ret == 1) ? a : a << 24; + result |= (ret == 2) ? b : b << 16; + result |= (ret == 3) ? c : c << 8; + result |= (ret == 4) ? d : d << 0; + return htonl(result); +} + +char* inet_ntoa(struct in_addr in) +{ + static char buffer[16]; + uint32_t he = ntohl(in.s_addr); + sprintf(buffer, "%u.%u.%u.%u", + (he >> 24) & 0xFF, + (he >> 16) & 0xFF, + (he >> 8) & 0xFF, + (he >> 0) & 0xFF + ); + return buffer; +}