1

I want to know in advance what network interface will be used for a given IP address X.

I could do that by browsing the result of java.net.NetworkInterface.getNetworkInterfaces() and checking X against the IP address and subnet mask of each InterfaceAddress returned by getInterfaceAddresses(), but it doesn’t seem like a lot of fun and I could end up with a different result from the one chosen by the IP stack if several choices are valid.

Why do I need that?

I need to know the IP address which can be used to reach me from the peer having the IP address X.

Julien Royer
  • 1,419
  • 1
  • 14
  • 27
  • For what purpose? NB the technique you describe isn't definitive. TCP does it via the static routing tables, not as you describe. – user207421 Jan 18 '16 at 11:56
  • @EJP I edited my post to add an explanation about my purpose (I hope that it is not too clumsy). – Julien Royer Jan 18 '16 at 13:12
  • @EJP If there are no static routes defined on a machine, I guess that the technique I describe is correct, isn’t it? – Julien Royer Jan 18 '16 at 13:13
  • You haven't really answered my question. *Why* do you need to know the IP address tha can be used to reach you from another peer? It's the peer that needs to know that, not you. And when he connects, you can get it from the socket. There is always at least one static route, – user207421 Jan 18 '16 at 23:22
  • @EJP I need to know it because the another peer is asking for it. I agree that he could retrieve it from the socket but I have no control over this code. – Julien Royer Jan 19 '16 at 14:00
  • @EJP I guess that my understanding of "static route" is not correct. – Julien Royer Jan 19 '16 at 14:07

1 Answers1

2

There's an answer here that I feel solves your problem.

But to expand on it a bit, the following code prints out the IP address of the interface you would use to route an IP packet from your host to the IP x.x.x.x.

DatagramSocket s = new DatagramSocket();
s.connect(InetAddress.getByAddress(new byte[]{x,x,x,x}), 0);
NetworkInterface n = NetworkInterface.getByInetAddress(s.getLocalAddress());
InetAddress yourInterfaceIP = n.getInetAddresses().nextElement();
System.out.println(yourInterfaceIP.getHostAddress());

Setting up a UDP datagram socket doesn't send anything. It just simply checks permissions and routing between the two end points. The IP you specify doesn't need to be reachable either for this to work.

This uses the routing present on the host your running this on. Obviously it doesn't use the routing on the remote host. So really, it returns what it considers a reachable interface from the perspective of X.

This obviously won't work behind a proxy, for which you'll need to use a whats-my-ip type service to look up what your proxy address is.

Community
  • 1
  • 1
AndyN
  • 2,075
  • 16
  • 25