Serenity Operating System
at hosted 92 lines 2.7 kB view raw
1/* 2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright notice, this 9 * list of conditions and the following disclaimer. 10 * 11 * 2. Redistributions in binary form must reproduce the above copyright notice, 12 * this list of conditions and the following disclaimer in the documentation 13 * and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27#include <arpa/inet.h> 28#include <errno.h> 29#include <netinet/in.h> 30#include <stdio.h> 31 32extern "C" { 33 34const char* inet_ntop(int af, const void* src, char* dst, socklen_t len) 35{ 36 if (af != AF_INET) { 37 errno = EAFNOSUPPORT; 38 return nullptr; 39 } 40 auto* bytes = (const unsigned char*)src; 41 snprintf(dst, len, "%u.%u.%u.%u", bytes[0], bytes[1], bytes[2], bytes[3]); 42 return (const char*)dst; 43} 44 45int inet_pton(int af, const char* src, void* dst) 46{ 47 if (af != AF_INET) { 48 errno = EAFNOSUPPORT; 49 return -1; 50 } 51 unsigned a; 52 unsigned b; 53 unsigned c; 54 unsigned d; 55 int count = sscanf(src, "%u.%u.%u.%u", &a, &b, &c, &d); 56 if (count != 4) { 57 errno = EINVAL; 58 return 0; 59 } 60 union { 61 struct { 62 uint8_t a; 63 uint8_t b; 64 uint8_t c; 65 uint8_t d; 66 }; 67 uint32_t l; 68 } u; 69 u.a = a; 70 u.b = b; 71 u.c = c; 72 u.d = d; 73 *(uint32_t*)dst = u.l; 74 return 1; 75} 76 77in_addr_t inet_addr(const char* str) 78{ 79 in_addr_t tmp; 80 int rc = inet_pton(AF_INET, str, &tmp); 81 if (rc < 0) 82 return INADDR_NONE; 83 return tmp; 84} 85 86char* inet_ntoa(struct in_addr in) 87{ 88 static char buffer[32]; 89 inet_ntop(AF_INET, &in.s_addr, buffer, sizeof(buffer)); 90 return buffer; 91} 92}