0

How can I find a java server on the LAN by giving the client only the network part of the IP address? Can I do it this way?

Socket sock = new Socket("10.10.10.*", 4444);
Chips
  • 117
  • 3
  • 10
  • Can you explain your question a little bit? – Pasupathi Rajamanickam Mar 18 '15 at 11:22
  • I need to find a java server on the network without knowing it IP address, my question is: can i pass the socket constructor only part of the server's IP address? – Chips Mar 18 '15 at 11:23
  • These ( [link1](http://docs.oracle.com/javase/7/docs/api/java/net/InetSocketAddress.html#InetSocketAddress(java.lang.String,%20int)) and [link2](http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#connect%28java.net.SocketAddress,%20int%29) ) are the droids, you are looking for. To determine the IP range, you need to get the [subnetmask](http://stackoverflow.com/questions/1221517/how-to-get-subnet-mask-using-java). You find the IP ranges [here](https://en.wikipedia.org/wiki/Classful_network). – SME_Dev Mar 18 '15 at 12:32

1 Answers1

5

I had the same problem and here is how I figured it out : UDP Broadcast. It will allow the client to connect to server regardless of its IP, so you don't have to hardcode the IP Address, only the port used for UDP (see below).

Here is how it works :

  1. Server watches port n
  2. Client sends packets at all ports n he can reach
  3. When a message reaches server's port, Server responses to the sender and includes its own IP address
  4. Client creates a socket and connect to the IP address he got from the server

Here is the tutorial that helped me : http://michieldemey.be/blog/network-discovery-using-udp-broadcast/

Jean
  • 1,707
  • 3
  • 24
  • 43
  • 2
    There could be a problem, if broadcasts are prohibited for the LAN. While simple Peer-to-Peer networks with a plain hub/switch could allow it (device dependent), you might get problems in an administrated domain network. – SME_Dev Mar 18 '15 at 13:47
  • `DatagramPacket#recieve` blocks until it receives a response. Is there a way (in a multithreaded program) to cancel receiving if no responses are sent and thus continue execution of the thread? – Cardinal System Dec 01 '17 at 22:55