Skip to content

Instantly share code, notes, and snippets.

@BrianLian
Created April 13, 2017 10:37
Show Gist options
  • Save BrianLian/9d0954792231ac935e4069754c58e9d1 to your computer and use it in GitHub Desktop.
Save BrianLian/9d0954792231ac935e4069754c58e9d1 to your computer and use it in GitHub Desktop.
convert ipV4 between uint and string
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int ipv4_to_string(uint32_t ipaddr, char *str) {
memset (str, 0, sizeof(char) * 50);
sprintf(str, "%d.%d.%d.%d", (ipaddr >> 24)&0xFF,
(ipaddr >> 16)&0xFF, (ipaddr >> 8)&0xFF, (ipaddr)&0xFF);
return 0;
}
uint32_t ipv4_to_uint(char *ipaddr) {
uint32_t ipV4 = 0;
uint32_t tmp;
char *pch;
pch = strtok (ipaddr,".");
do {
tmp = atoi(pch);
ipV4 = (ipV4 << 8) | tmp;
pch = strtok (NULL, ".");
} while (pch != NULL);
return ipV4;
}
int main() {
uint32_t ipV4;
char ipV4_s[50];
ipV4 = 3764655192ul; // 224.100.20.88
printf("Origin: ip : 224.100.20.88\n");
printf("Origin: ip in hex: 0x%X\n\n", ipV4);
ipv4_to_string(ipV4, ipV4_s);
printf("ip: %s\n", ipV4_s);
ipV4 = ipv4_to_uint(ipV4_s);
printf("ip in hex: 0x%X\n", ipV4);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment