inet_ntop(), inet_pton(), htonl(), ntohl()

1. inet_ntop()、inet_pton() : 点分十进制字符串(dotted-decimal notation)与网络字节序(network byte order)二进制数值互转

//inet_ntop()函数原型
PCSTR
WSAAPI
inet_ntop(
    _In_                                INT             Family,
    _In_                                PVOID           pAddr,
    _Out_writes_(StringBufSize)         PSTR            pStringBuf,
    _In_                                size_t          StringBufSize
    );
//inet_ntop示例
SOCKADDR_IN addr;
int len = sizeof(SOCKADDR_IN); socket_client = accept(socket_server, (sockaddr*)&addr, &len); char *address = new char; inet_ntop(AF_INET, &(addr.sin_addr.S_un.S_addr), address,sizeof(SOCKADDR_IN));//将网络字节顺序排列的IP转换为字符串IP

 

//inet_pton函数原型
WINSOCK_API_LINKAGE
   INT
   WSAAPI
   inet_pton(
   _In_                                      INT             Family,
   _In_                                      PCSTR           pszAddrString,
   _Out_writes_bytes_(sizeof(IN6_ADDR))      PVOID           pAddrBuf
   );
//inet_pton示例
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(3050);
//addr.sin_addr.S_un.S_addr = inet_addr("192.168.0.101");
int re_inetpton = inet_pton(AF_INET, "192.168.0.101", &(addr.sin_addr.S_un.S_addr));//将点分十进制串转换成网络字节序二进制值,此函数对IPv4地址和IPv6地址都能处理。
if (SOCKET_ERROR == connect(socket_client, (sockaddr*)&addr, sizeof(sockaddr)))
{
    AfxMessageBox(_T("服务器连接失败"));
    return;
}

 

2. htons()、ntohs(): 网络字节序(network byte order)与主机字节序(host byte order)互转

  uint32_t htonl(uint32_t hostlong);  

  uint16_t htons(uint16_t hostshort);  

  uint32_t ntohl(uint32_t netlong);  

  uint16_t ntohs(uint16_t netshort);  

//htons()函数示例
SOCKADDR_IN addr;
memset(&addr, 0, sizeof(SOCKADDR_IN));
addr.sin_port = htons(80);

 

 

 

posted on 2017-03-02 10:29  czhoud  阅读(4455)  评论(0编辑  收藏  举报

导航