Search code examples
c++csocketsproxysystems-programming

What is the POSIX call to determine the intended IP of a redirected socket open request?


I am modifying my hosts file to change the IP address of (for example a database call) to a local proxy that I am writing.

10.1.2.3 localhost
10.1.2.4 localhost

I want the proxy listening on the socket to work out which machine the socket opening request intended to go to. eg in my client I am calling.

dbPort = 4000;
openDatabaseConnection("10.1.2.3", dbPort);
...
openDatabaseConnection("10.1.2.4", dbPort);

So both call on the same socket. I want my proxy server to listen on 4000 and redirect the one going to 10.1.2.3 to the correct server by intended IP address.

Is there a POSIX call to get this from the socket header?

My question is: What is the POSIX call to determine the intended IP of a redirected socket open request?


Solution

  • No there is no way of knowing which IP-address was used in the client program. The hosts-file defines a set of aliases, and the aliases are replaced with the actual address (in your case localhost) by the name/address resolver, making you lose all information about the alias used. There is no "redirection" made, the alias substitution is made before the client even connects.

    The simplest way to solve your problem is not to use IP-address aliasing through the hosts file, but to use different port numbers.

    You could probably also add "virtual" interfaces for the different addresses, and have the proxy-server listen for connections on both those interfaces.