4

My question is based on the following understanding

  • Socket is defined by ip:port. Both server and client will have their own socket
  • Socket connection is defined by five touples server_ip, server_port, client_ip, client_port, protocol
  • A socket descriptor is an integer value that identifies a socket

I tried to implement my own server where socket() and accept() returns different socket descriptor value (Is it always the case?). My question is why is it said that accept() creates a new socket if no new port is opened in server and ip:port is same for both the socket descriptors returned by socket() and accept(). If new socket is created by accept() how is it different than the socket created by socket()?

Farsan Rashid
  • 1,460
  • 4
  • 17
  • 28
  • *"Socket connection is defined by..."* - The connection is usually the 4-tuple *`{server_ip, server_port, client_ip, client_port}`* in most networks because TCP/IP is usually implied. Or maybe, a TCP/IP connection is the 4-tuple. – jww Jun 07 '18 at 14:34
  • 1
    @jww `protocol` is also included in identifying a unique connection, since multiple protocols can be running on the same IP:port at the same time. For instance, TCP and UDP, and in some cases, even IPv4 and IPv6. – Remy Lebeau Jun 07 '18 at 16:59

1 Answers1

10
  1. I tried to implement my own server where socket() and accept() returns different socket descriptor value (Is it always the case?).

Yes.

  1. My question is why is it said that accept() creates a new socket if no new port is opened in server and ip:port is same for both the socket descriptors returned by socket() and accept(). If new socket is created by accept() how is it different than the socket created by socket()?

Because the initial socket is used to wait for communication while the second is used to communicate. A call to socket (+bind+listen) prepare a communication end-point, aka socket (or server socket) to receive incoming calls. A call to accept on a well prepared communication point, waits for an incoming call, and when this happens that creates a communication channel (2 end-points + protocol) represented by the connected socket returned by the call.

C API may confuse you because both are called socket, but are really not for the same use. In some other languages/API differentiation is made. For example in Java you have ServerSocket that is used to wait for incoming calls, and Socket that are used to communicate.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • Definitely by distinguishing socket and connected socket things become easy to understand. Let's wait to see if others have something to say before accepting your answer. – Farsan Rashid Jun 07 '18 at 17:20