虽然我得到了来自下面的代码段端口号非零值,则返回值的端口不匹配值的端口用于建立套接字:
#include <winsock2.h>
int main(void)
{
SOCKADDR_IN server;
WSADATA wsa;
SOCKET s;
DWORD dwTime = 1000;
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
//handle error
}
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
//handle error
}
if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&dwTime, sizeof(dwTime)) == SOCKET_ERROR)
{
//handle error
}
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 5000 );
//Connect to server
if(connect(s , (struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
//handle error
}
//read port number
size_t lensin = sizeof(server);
if (getsockname(s, (struct sockaddr *)&server, &lensin) == SOCKET_ERROR)
perror("getsockname");
else
{
printf("port number, no byte order reversal: %u\n", server.sin_port);
printf("port number, with byte order reversal: %u\n", ntohs(server.sin_port));
}
return 0;
}
对于端口是5000,我得到以下值:
具有或不具有字节顺序反转(使用ntohs()
该值仍然是不一样的。 我怎样才能读取用于建立在首位的连接端口号的整数值?