IPv4通訊端地址結構:
#include <netinet/in.h>struct in_addr{ in_addr_t s_addr; /*32-bit,network byte orderd*/};struct sockaddr_in{ uint8 sin_len; sa_family_t sin_family; /*AF_INET*/ in_port_t sin_port; /*16-bit,network byte ordered*/ struct in_addr sin_addr; char sin_zero[8];};
s_addr可以為宏 INADDR_ANY
地址轉換函式:
#include <netinet/in.h>int inet_aton(const char *strptr, struct in_addr *addrptr);char *inet_ntoa(struct in_addr inaddr);
inet_aton將strptr所指的C字串轉換成一個32位的網路位元組序二進位值,並通過指標addrptr來儲存。若成功則返回1,否則返回0。
ps:gcc編譯時間,如果用--std=c99選項,編譯器會給出警告:“warning: implicit declaration of function ‘inet_aton’”,可以用--std=gnu99代替--std=c99,原因在這:http://stackoverflow.com/questions/1783792/why-does-gcc-report-implicit-declaration-of-function-round
inet_ntoa將32位的網路位元組序二進位IPv4地址轉換成相應的點分十進位數串。該函數傳回值指向一個靜態記憶體地區。所以是不可重新進入。如果你要用到這個返回的字串的話,最好自己拷貝出來。
位元組排序函數:
uint16_t htons(uint16_t host16bitvalue);uint32_t htonl(uint32_t host32bitvalue); /*返回網路位元組序的值*/uint16_t ntohs(uint16_t net16bitvalue);uint32_t ntohl(uint32_t net32bitvalue); /*返回主機位元組序的值*/
16:表示是16bit的值;32:表示是32bit的值;
s:短整數,即16bit; l:長整數,即32bit;
h:本地主機位元組; n:網路位元組;