Question

I'm new to socket programing, so forgive me if this question is basic; I couldn't find an answer anywhere.

What constitutes requiring a new socket?

For example, it appears possible to send and receive with the same socket fd on the same port. Could you send on port XXXX and receive on port YYYY with one socket? If not, then are sockets specific to host/port combinations?

Thanks for the insight!

Was it helpful?

Solution

A socket establishes an "endpoint", which consists of an IP address and a port:

Yes, a single socket is specific to a single host/port combination.

READING RECOMMENDATION:

Beej's Guide to Network Programming:

Unix Network Programming: Stevens et al:

OTHER TIPS

Port number is a local property and helps identify a socket endpoint for an incoming data destined for that port on the receivers machine. Each machine has 64K ports for each protocol type (TCP or UDP) and for each family type (IPv4 or IPv6).

With UDP, it is possible to send to (and receive from) many clients sitting on different ports. So, for the following connection:

UDP_socketA (port p1) <---------> UDP socketB (port p2)
     |
     |
     |
     |
UDP socketC (port p3)

Thus, socketA can send datat to socketB and socketC even though they are sitting on different port numbers. The way it works is that with UDP sockets, we typically use sendto() API that allows us to specify an IP address and a port number for each packet. Thus, we can send one packet to port B and the next packet to port C and what not.

With TCP, however this is not the case. Once a connection is established, let us say between socketA and socketB, then there is no way, either of these sockets can talk to socketC

TCP_socketA (port p1) <---------> TCP socket B (port p2)
         |
         |
         |
         |
    TCP socketC (port p3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top