Retrieving port number using winsock sockets API

2019-08-08 18:57发布

Although I do get a non-zero value for port number from the code segment below, the value returned for port does not match the value for port used to establish the socket:

#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;
}

For port 5000, I get the following value:
enter image description here

With or without byte order reversal (using ntohs()), the value is still not the same. How can I read the integer value for port number that was used to establish the connection in the first place?

1条回答
Deceive 欺骗
2楼-- · 2019-08-08 19:31

getsockname() returns the local port number. Since your socket was not bound to a specific local port when you called connect(), a random ephemeral port got chosen, port 56179.

If you want the port number you connected to, use getpeername()

查看更多
登录 后发表回答