Skip to content

Instantly share code, notes, and snippets.

@Voldrix
Created January 8, 2024 21:21
Show Gist options
  • Save Voldrix/94f01ae8696d7ecf3a9236c210e812c0 to your computer and use it in GitHub Desktop.
Save Voldrix/94f01ae8696d7ecf3a9236c210e812c0 to your computer and use it in GitHub Desktop.
IP Address to String Conversion in C
//convert an integer IPv4 address to a string OR a string to an integer IPv4 address
//STR to IP
static unsigned int str_to_ip(char *str) {
//assumes str is properly formatted IPv4 address
register unsigned int ip, octet;
register char *tail = str;
while(*tail++)
; //work backwards to track decimal position
tail -= 2;
ip = *tail-- - '0';
ip += (*tail == '.') ? 0 : (*tail-- - '0') * 10;
ip += (*tail == '.') ? 0 : (*tail-- - '0') * 100;
tail -= 1;
octet = *tail-- - '0';
octet += (*tail == '.') ? 0 : (*tail-- - '0') * 10;
octet += (*tail == '.') ? 0 : (*tail-- - '0') * 100;
tail -= 1;
ip |= octet << 8;
octet = *tail-- - '0';
octet += (*tail == '.') ? 0 : (*tail-- - '0') * 10;
octet += (*tail == '.') ? 0 : (*tail-- - '0') * 100;
tail -= 1;
ip |= octet << 16;
octet = *tail-- - '0';
octet += (tail < str) ? 0 : (*tail-- - '0') * 10;
octet += (tail < str) ? 0 : (*tail - '0') * 100;
ip |= octet << 24;
//IP in network byte order (big-endian)
return ip;
}
//IP to STR
static unsigned int ip_to_str(unsigned int ip, unsigned char* buff) {
//IP in network byte order (big-endian)
//buffer must be at least 16 char/bytes
register unsigned char *tail = buff, tmp;
register unsigned int n, num, count = 0;
unsigned char octet[4];
//compute octets in reverse order, because they will need to be reversed later
octet[0] = ip & 255;
octet[1] = (ip >> 8) & 255;
octet[2] = (ip >> 16) & 255;
octet[3] = ip >> 24;
for(int i = 0; i < 4; i++) {
num = octet[i];
*tail = '0';
tail += !num; //in case of octet == 0
count += !num;
//print decimal values backwards. required for decimal position tracking
while(num > 0) {
n = num % 10;
num /= 10;
*tail++ = n + '0';
count += 1;
}
*tail++ = '.';
}
count += 3;
tail -= 1;
*tail-- = 0; //overwrite trailing '.' with null terminator
//reverse whole string, decimal values and octet order.
while(buff < tail) {
tmp = *buff;
*buff++ = *tail;
*tail-- = tmp;
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment