Created
August 7, 2018 12:55
-
-
Save nasacj/ea465f2841b6d5ef34f317c1497b63ab to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <stdio.h> | |
#include <cassert> | |
static __inline int isdigit(char c) | |
{ | |
return c >= '0' && c <= '9'; | |
} | |
int aton(const char* ip, int* inet_addr) { | |
uint32_t val; | |
char c; | |
unsigned int parts[4] = {0}; | |
unsigned int * pp = parts; | |
int saw_digit = 0; | |
int num_read = 0; | |
while((c = *ip++) != '\0') { | |
if (isdigit(c)) { | |
val = (val * 10) + (c - '0'); | |
if (val > 255) { | |
return 0; | |
} | |
if (! saw_digit) { | |
if (++num_read > 4) { | |
return 0; | |
} | |
saw_digit = 1; | |
} | |
} | |
else if (c == '.' && saw_digit) { | |
if (num_read == 4) { | |
return 0; | |
} | |
*pp++ = val; | |
saw_digit = 0; | |
val = 0; | |
} else { | |
return 0; | |
} | |
} | |
if (num_read < 4) { | |
return 0; | |
} | |
val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); | |
*inet_addr = val; | |
} | |
int main() { | |
const char* ip = "101.227.12.253"; | |
int addr = 0; | |
if (aton(ip, &addr)) { | |
printf("addr_int = %d", addr); | |
} | |
assert(addr == 1709378813); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment