使用winsock套接字API检索端口号

时间:2015-06-02 17:59:54

标签: c sockets winsock

虽然我从下面的代码段获得了端口号的非零值,但是为端口返回的值与用于建立套接字的端口值不匹配:

#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,我得到以下值:
enter image description here

有或没有字节顺序反转(使用ntohs()),值仍然不相同。如何读取首先用于建立连接的端口号的整数值?

1 个答案:

答案 0 :(得分:3)

getsockname()返回本地端口号。由于在调用connect()时套接字未绑定到特定的本地端口,因此选择了随机ephemeral port,端口为56179。

如果您需要连接的端口号,请使用getpeername()