用winsock套接字API获取端口号 [英] Retrieving port number using winsock sockets API

查看:595
本文介绍了用winsock套接字API获取端口号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我得到了来自下面的code段的端口号为非零值,返回端口值不匹配的值端口用于建立套接字:

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

有关端口是5000,我得到以下值:结果

For port 5000, I get the following value:

带或不带字节顺序反转(使用 ntohs和()),该值仍然不一样的。我怎样才能读取用来建立在首位的连接端口号的整数值?

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?

推荐答案

getsockname()返回本地端口号。由于您的插座不绑定到特定的本地端口,当你叫连接(),随机临时端口得到选择,端口56179。

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.

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

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

这篇关于用winsock套接字API获取端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆