简体   繁体   中英

Binding a port for client tcp socket

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM