1. 程式人生 > >linux網路地址轉換函式

linux網路地址轉換函式

在socket程式設計時,會出現指定了ip,埠號,卻連不上,這是因為網路地址跟本地主機地址的字元順序不一樣導致的。

在linux下提供了一些操作函式,如下:

unsigned long int htonl(unsigned long int hostlong);

用來將引數指定的32位hostlong 轉換成網路字元順序。

unsigned short int htons(unsigned short int hostshort);

用來將引數指定的16位hostshort轉換成網路字元順序。

unsigned long int inet_addr(const char *cp);

用來將引數cp所指的網路地址字串轉換成網路所使用的二進位制數字。

網路地址字串是以數字和點組成的字串,例如:“163.13.132.68”。

int inet_aton(const char * cp,struct in_addr *inp);

用來將引數cp所指的網路地址字串轉換成網路使用的二進位制的數字,然後存於引數inp所指的in_addr結構中。

char * inet_ntoa(struct in_addr in);

用來將引數in所指的網路二進位制的數字轉換成網路地址,然後將指向此網路地址字串的指標返回

unsigned long inet_network(const char *addr);

這個函式需要一個在引數addr中包含一個點分隔的地址輸入字串。

返回值是主機順序的IP地址的32位值

The inet_lnaof() function returns the local host address part of

the Internet address in. The local host address is returned in local host byte order.

The inet_netof() function returns the network number part of the Internet Address in.

The network number is returned in local host byte order.