3

How I can bind a Java Socket to listen every loopback address?

http://en.wikipedia.org/wiki/Localhost "IPv4 network standards reserve the entire 127.0.0.0/8 address block for loopback purposes. That means any packet sent to one of those 16,777,214 addresses (127.0.0.1 through 127.255.255.254) will be looped back."

The current implementation binds only to localhost/127.0.0.1 using SocketImpl.bind(InetAddress host, int port). This was under assumption that the machine name would resolve same as localhost, i.e. 127.0.0.1, but it seems on linux the machine hostname might be bound to 127.0.1.1 (e.g. see https://serverfault.com/questions/363095/why-does-my-hostname-appear-with-the-address-127-0-1-1-rather-than-127-0-0-1-in).

Another software locally uses the machine's host name to resolve which IP to connect => tries to connect 127.0.1.1, which the server does not listen because it is bound only to 127.0.0.1.

That serverfault's question answer links to https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=316099 , which says: "most services that listen locally listen on all 127/8 addresses, not just on 127.0.0.1." So that's what I would like to do.

Is there any way to do this? or should I hope binding to 127.0.0.1 and 127.0.1.1 is enough?

Community
  • 1
  • 1
Bjarne Boström
  • 227
  • 1
  • 4
  • 14
  • Just as a note, since I can edit both applications, I can workaround this by just using "localhost" or 127.0.0.1 instead of the machine's hostname. Just wanted to know if it is possible to listen every loopback address in Java. – Bjarne Boström Dec 18 '14 at 14:10
  • Or actually it is possible that there are other clients not under my control so this might actually be a bigger problem. – Bjarne Boström Dec 18 '14 at 14:17
  • Well, you could list all configured network interfaces http://stackoverflow.com/questions/19227781/linux-getting-all-network-interface-names – user3159253 Dec 18 '14 at 14:25
  • Do you need to avoid binding to non-loopback addresses? Because it's easy to bind to all interfaces. – Alan Stokes Dec 18 '14 at 14:30
  • User of the server application can define a set of InetAddresses which to bind, so yes. But to my knowledge an InetAddress can only point to a single IP address, therefore I would need 16M instances of InetAddress which of course is not usable. – Bjarne Boström Dec 18 '14 at 14:37
  • 2
    The bug report is wrong and what it describes is impossible. A listening socket can be bound to either one IP address or all of them: nothing else. – user207421 Dec 18 '14 at 15:40

0 Answers0