1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include <arpa/inet.h> 18 #include <netinet/in.h> 19 #include <stdlib.h> 20 21 #include "private/ErrnoRestorer.h" 22 23 // The difference between inet_network(3) and inet_addr(3) is that 24 // inet_network uses host order and inet_addr network order. inet_network(const char * cp)25in_addr_t inet_network(const char* cp) { 26 in_addr_t network_order = inet_addr(cp); 27 return ntohl(network_order); 28 } 29 inet_addr(const char * cp)30in_addr_t inet_addr(const char* cp) { 31 in_addr addr; 32 return inet_aton(cp, &addr) ? addr.s_addr : INADDR_NONE; 33 } 34 inet_aton(const char * cp,in_addr * addr)35int inet_aton(const char* cp, in_addr* addr) { 36 ErrnoRestorer errno_restorer; 37 38 unsigned long parts[4]; 39 size_t i; 40 for (i = 0; i < 4; ++i) { 41 char* end; 42 errno = 0; 43 parts[i] = strtoul(cp, &end, 0); 44 if (errno != 0 || end == cp || (*end != '.' && *end != '\0')) return 0; 45 if (*end == '\0') break; 46 cp = end + 1; 47 } 48 49 uint32_t result = 0; 50 if (i == 0) { 51 // a (a 32-bit). 52 if (parts[0] > 0xffffffff) return 0; 53 result = parts[0]; 54 } else if (i == 1) { 55 // a.b (b 24-bit). 56 if (parts[0] > 0xff || parts[1] > 0xffffff) return 0; 57 result = (parts[0] << 24) | parts[1]; 58 } else if (i == 2) { 59 // a.b.c (c 16-bit). 60 if (parts[0] > 0xff || parts[1] > 0xff || parts[2] > 0xffff) return 0; 61 result = (parts[0] << 24) | (parts[1] << 16) | parts[2]; 62 } else if (i == 3) { 63 // a.b.c.d (d 8-bit). 64 if (parts[0] > 0xff || parts[1] > 0xff || parts[2] > 0xff || parts[3] > 0xff) return 0; 65 result = (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]; 66 } else { 67 return 0; 68 } 69 70 if (addr != nullptr) addr->s_addr = htonl(result); 71 return 1; 72 } 73