Networking – can TCP client use the same port to connec to different remote TCP servers

networkingtcp

I'm wondering whether TCP client can use the same port to connec to different remote TCP servers or not?

In network-programming, there are two functions: sendto and send. When WE use send we don't need to specify the destination. This seems to mean that a connected tcp socket can only be related to one (src ip, src port, dst ip, dst port) 4-tuple.

can I do something like:

 sockfd=socket(AF_INET,SOCK_STREAM,0);

 bzero(&cliaddr,sizeof(cliaddr));
 cliaddr.sin_family = AF_INET;
 cliaddr.sin_addr.s_addr=inet_addr(local_ip);
 cliaddr.sin_port=htons(32000);

 bind(listenfd,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
 connect(sockfd, (struct sockaddr *)&servaddr1, sizeof(servaddr1));
 connect(sockfd, (struct sockaddr *)&servaddr2, sizeof(servaddr2));

 sendto(sockfd, buf, len, 0, (struct sockaddr *)&servaddr1, socklen);
 sendto(sockfd, buf, len, 0, (struct sockaddr *)&servaddr2, socklen);

for example, is it possible http proxy may run out of ports and have to reuse ports?

Best Answer

To answer this question we may need to differentiate between TCP, the API-agnostic protocol, and BSD Sockets, the most well-known and widely-adopted API by which apps access the features of their OSes' TCP stacks.

TCP, the protocol, as you've already noted, considers each 4-tuple (src ip, src port, dst ip, dst port) to be a separate connection. Change any one of the items in that 4-tuple and it's a totally separate connection. So, Yes, TCP the protocol can handle multiple connections from a single source IP address and source port.

Whether or not there's an easy way to access that functionality from the venerable BSD Sockets API may be a different question.

Related Question