-2

In virtual hosting via IP address or virtual hosting via port number, a web server decides which web site to serve based on the IP address or port number that a request was sent to.

When a web server receives a HTTP request, how can it know the IP address and port number to which the request was sent?

Does the request contain the IP address and port number, and if yes, does the server read the IP address and port number from the request?

If not, does the web server call some function in the socket library to get the IP address and port number?

Thanks.

Tim
  • 1,487
  • 6
  • 28
  • 43

1 Answers1

4

The web server uses an operating system TCP stack socket to talk to remote endpoints via TCP protocol.

This socket has information on the endpoint, including the IP address and the port the remote endpoint used to connect to the socket. This information can be retrieved using getsockopt() function with proper arguments.

So, the answer is that web server reads the remote IP address from socket options.

Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63
  • Thanks. Does the web server need to call accept() first to create a new socket, and then call getsockopt() on the new socket to get the IP address and port number? – Tim Feb 13 '19 at 19:20
  • 1
    I don't know the details, but you can quite easily use Google to find the exact way it goes. – Tero Kilkanen Feb 13 '19 at 22:18