Binding a port for client tcp socket

蹲街弑〆低调 提交于 2021-01-29 15:44:56

问题


I have a problem about 'binging a local port for a client tcp socket'.
The code is as below:

void tcpv4_cli_connect(const char *srvhost, in_port_t srvport,
                       const char *clihost, in_port_t cliport)
{
    struct sockaddr_in srvaddr, cliaddr;
    struct in_addr     inaddr;
    int sockfd;

    bzero(&srvaddr, sizeof(srvaddr));
    inet_aton(srvhost, &inaddr);
    srvaddr.sin_family = AF_INET;
    srvaddr.sin_addr   = inaddr;
    srvaddr.sin_port   = htons(srvport);

    bzero(&cliaddr, sizeof(cliaddr));
    inet_aton(clihost, &inaddr);
    cliaddr.sin_family = AF_INET;
    cliaddr.sin_addr   = inaddr;
    cliaddr.sin_port   = htons(cliport);

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    bind(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr));

    if (connect(sockfd, (struct sockaddr *) &srvaddr, sizeof(srvaddr)) != 0)
        perror("Something Wrong");
    return;
}


int main(int argc, char *argv[])
{    
    // Wrong for "220.181.111.86", but ok for "127.0.0.1"
    tcpv4_cli_connect("220.181.111.86", 80, "127.0.0.1", 40888);
    return 0;
}  

When I do tcpv4_cli_connect("220.181.111.86", 80, "127.0.0.1", 40888) in main function, (220.181.111.86 is an address on Internet), an error will show up: Something Wrong: Invalid argument.

And if I comment bind(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr)) in the code, things will be fine and a random port is used for client socket.

But it is alright when I do tcpv4_cli_connect("127.0.0.1", 80, "127.0.0.1", 40888) whether or not binding a port to client socket.

What does Invalid argument mean for a connect operation? I wonder if it is only allowed to bind a specific port for the client to connect to local address? Clients can only use random port to connect to a external server?
Is there someting I misunderstood?

/br
Ruan


回答1:


When you bind() to 127.0.0.1 (INADDR_LOOPBACK), you are binding to a loopback interface that does not have access to the outside world, only to itself, so you cannot connect() to any IP other than 127.0.0.1. If you want to bind() to a local interface when you connect() to an outside server, you have to bind to the actual IP of an interface that is connected to a network that can reach that server.

If all you want to do is bind() to a specific port, but allow the OS to pick an appropriate interface for you, then bind to 0.0.0.0 (INADDR_ANY) instead.



来源:https://stackoverflow.com/questions/26477775/binding-a-port-for-client-tcp-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!