0

When the application layer sends the data to the Transport layer to deliver to the server, how does it know which port number to communicate to?

Precisely, the TCP segment contains as a header the destination port no., how does it determine it?

2 Answers 2

1

The application has to be told. Either the port is a standard port listed in etc/services, in which case the getaddrinfo() API tells you, or else it is provided via the application's configuration, or it's hard-wired into the source code.

0

The application establishes the port number when it creates a socket connection to the server. The socket knows which local IP/Port it is bound to and which remote IP/Port it is connected to. Those values are used whenever data is sent using that socket. The transport layer knows which values to put in the IP and TCP headers.

5
  • That's exactly my question. How does socket know which remote port it' bound to?
    – Sankalp
    Jul 3, 2013 at 3:30
  • It is an attribute of the socket. The local IP/Port can be retrieved using getsockname() at any time once the socket has been bound locally (bind() or accept()). The remote IP/Port can be retrieved using getpeername() at any time once the connection has been established (connect() or accept()). Just think of a socket as a struct that contains all kinds of behavioral fields, which can be accessed/assigned through various socket API functions. The actual storage of that info is an implementation detail of the OS. Jul 3, 2013 at 4:12
  • Again, it will keep digging. It's true that socket API can return the destination port number to the application program, but how does the API actually get it? Is it hard coded as mentioned by @EJP ?
    – Sankalp
    Jul 3, 2013 at 4:39
  • For the socket to get the initial values, the application has to tell the socket what they are, via the API functions I mentioned earlier. The socket then remembers them and uses them when interacting with the transport layer. Jul 3, 2013 at 6:14
  • Don't misquote me. I didn't say anything about the port number being hard coded into the socket API. I said it may be hard coded into the application, as one of several alternatives.
    – user207421
    Jul 16, 2013 at 1:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.