2011-03-16 190 views

回答

89

使用inet_ntop()inet_pton()如果您需要其他方法。不要使用inet_ntoa(), inet_aton()和類似的,因爲它們已被棄用,不支持ipv6。

這裏有一個不錯的guide有不少例子。

// IPv4 demo of inet_ntop() and inet_pton() 

struct sockaddr_in sa; 
char str[INET_ADDRSTRLEN]; 

// store this IP address in sa: 
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr)); 

// now get it back and print it 
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN); 

printf("%s\n", str); // prints "192.0.2.33" 
+0

我應該怎麼做才能在Windows下使用它們? 我應該包括什麼? – Safari 2011-03-16 16:41:27

+4

如果在Windows Vista和更高版本上使用winsock,則使用InetNtop和InetPton。頭文件Ws2tcpip.h。小技巧是看msdn上的例子。 – Milan 2011-03-16 16:46:32

+0

我使用Windows XP。 – Safari 2011-03-16 16:55:31

3

inet_ntoa()轉換一個in_addr字符串:

的INET_NTOA功能的 (IPv4)Internet上的網絡地址轉換成 在Internet標準 點分十進制格式的ASCII字符串。

inet_addr()做相反的作業

的inet_addr函數轉換包含IPv4 點分十進制地址轉換成一個適當的 地址IN_ADDR結構

PS一個 字符串這個首先搜索結果「in_addr to string」!

+5

這些功能已被棄用,不應該被使用。 – Milan 2011-03-16 16:13:03

+1

@Milan行。儘管OP使用in_addr結構來處理ipv4 – CharlesB 2011-03-16 16:15:08

+0

我應該如何在Windows下使用它們? 我應該包括什麼? – Safari 2011-03-16 16:41:47

4

我不知道我是否正確理解了這個問題。

反正你找這樣的:

std::string ip ="192.168.1.54"; 
std::stringstream s(ip); 
int a,b,c,d; //to store the 4 ints 
char ch; //to temporarily store the '.' 
s >> a >> ch >> b >> ch >> c >> ch >> d; 
std::cout << a << " " << b << " " << c << " "<< d; 

Output:

192 168 1 54 
1

要字符串轉換爲-地址:

in_addr maskAddr; 
inet_aton(netMaskStr, &maskAddr); 

要組in_addr轉換成字符串:

char saddr[INET_ADDRSTRLEN]; 
inet_ntop(AF_INET, &inaddr, saddr, INET_ADDRSTRLEN); 
4

我可以將字符串轉換爲DWORD和背部與此代碼:

char strAddr[] = "127.0.0.1" 
DWORD ip = inet_addr(strAddr); // ip contains 16777343 [0x0100007f in hex] 

struct in_addr paddr; 
paddr.S_un.S_addr = ip; 

char *strAdd2 = inet_ntoa(paddr); // strAdd2 contains the same string as strAdd 

我在舊MFC代碼維護項目的工作,所以不推薦使用轉換函數的調用是不適用的。

0

這個例子說明了如何從字符串轉換爲IP,反之亦然:

struct sockaddr_in sa; 
char ip_saver[INET_ADDRSTRLEN]; 

// store this IP address in sa: 
inet_pton(AF_INET, "192.0.1.10", &(sa.sin_addr)); 

// now get it back 
sprintf(ip_saver, "%s", sa.sin_addr)); 

// prints "192.0.2.10" 
printf("%s\n", ip_saver); 
相關問題