2011年3月25日 星期五

Handle IP address convert to int or char(dot IP)

This code will do
1. convert char IP address to four int
2. convert four int var to one int
3. convert four int var to one char
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include 
int main() {
 char arr[] = "192.168.1.102\0 "; //extended to be able to fit up to maximum length
 unsigned short a, b, c, d;
 sscanf(arr, "%hu.%hu.%hu.%hu", &a, &b, &c, &d );
 arr[0] = '\0'; // cleared to make sure it's not just the same string coming back
 unsigned long ipAddr = ( a << 24 ) | ( b << 16 ) | ( c << 8 ) | d;
 a = (ipAddr & (0xff << 24)) >> 24;
 b = (ipAddr & (0xff << 16)) >> 16;
 c = (ipAddr & (0xff << 8)) >> 8;
 d = ipAddr & 0xff;
 sprintf(arr, "%hu.%hu.%hu.%hu", a, b, c, d);
 puts(arr);
}


Or, these is a api to do it

1
2
3
4
5
6
7
8
9
10
11
int main()
{ char ip[] = "192.168.1.102"; long long_address = inet_addr (ip) ; struct in_addr addr; addr.s_addr = long_address; char *dot_ip = inet_ntoa(addr); printf("%s",dot_ip); }


===========================================
reference from:
http://www.cplusplus.com/forum/general/9403/
http://stackoverflow.com/questions/1505676/how-to-convert-ip-address-from-char-to-int
http://beej.us/guide/bgnet/output/html/multipage/inet_ntopman.html  (good)
http://beej.us/guide/bgnet/output/html/multipage/inet_ntoaman.html
http://www.aboutmyip.com/AboutMyXApp/IP2Integer.jsp
===========================================


後記:
後來發現一篇文章最有用

從 inet_ntoa 看 thread safe 的 API


inet_ntoa會有thread safe的問題,最好直接改用inet_ntop

沒有留言: