Linux socket 地址及常用函数


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  &nbsp; &nbsp;sin_family;      &nbsp; &nbsp;/*AF_INET*/
  in_port_t      sin_port;      &nbsp; &nbsp; /*16-bit,network byte ordered*/
  struct in_addr &nbsp;sin_addr;
  char    &nbsp; &nbsp; &nbsp; &nbsp;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,原因在这里。

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:网络字节;

相关内容