1

I recently started working with sockets in Java and I bounded my server socket with the IP address returned by the static method InetAddress.getLocalHost() With this my client side was able to connect to the server in most of the cases.

However, it didn't work when my server computer had complex networking. The static method InetAddress.getLocalHost() returned an address which wasn't reachable by the client machine

I want to know, how can one get the ip address which is reachable by other devices connected to the same network through Java?

MASHED TRACKS
  • 120
  • 1
  • 9
  • What is the address returned by `InetAddress.getLocalHost()` and why is it not reachable from the client? This sounds more like a network administration problem. – Progman May 19 '19 at 18:06
  • Since the computer has many interfaces and each interface can be bounded with any possible address, I read somewhere that InetAddress.getLocalHost() is not so reliable with a complex network – MASHED TRACKS May 19 '19 at 18:12
  • I suggest you look here: [How to Determine Internet Network Interface in Java](https://stackoverflow.com/questions/8462498/how-to-determine-internet-network-interface-in-java) and fit the answer to your needs – matanper May 19 '19 at 19:52

1 Answers1

0

InetAddress.getLocalHost() is the address that is mapped to your host's name. That's really all it says. What you get back from this may or may not be what you want too bind a socket to, depending on your host and network setup, and your intentions.

A socket binds to one or more network interfaces and will listen on those interfaces. You can get the list of all interfaces via the call:

NetworkInterface.getNetworkInterfaces()

I believe that you can also bind to the address "0.0.0.0", which says to bind to all of your network interfaces. I've used this in the past, but I don't know if it is supported by the basic socket API.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44