title: Dynamically find other hosts in a LAN in Java
body: <p>A while ago I developed a little LAN chat app. in Java which allows chatting with other hosts, send images, etc. Although it was created just for fun, now it's being used where I work.</p>
  
  <p>Currently, there is no <em>"chat server"</em> on the app. where each client registers, updates it's status, etc. (I liked the idea of symmetric design and not depending on a server running on some other machine).  </p>
  
  <p>Instead, each host is a client/server which has a <strong>hosts.properties</strong> file with the hostname of the other hosts, and - for instance - broadcasts to each one of them when sending a massive message/image/whatever.</p>
  
  <p>In the beginning there were just a couple of hosts, so this <strong>hosts.properties</strong> file wasn't an issue.  But as the amount of users increased, the need of updating that file was a bit daunting.  So now I've decided to get rid of it, and each time the app. starts, dynammically find the other active hosts.</p>
  
  <p>However, I cannot find the correct way of implement this.  I've tried starting different threads, each one of them searching for other hosts in a known range of IP addresses.  Something like this (simplified for the sake of readability):</p>
  
  <pre><code>/** HostsLocator */
  public static void searchForHosts(boolean waitToEnd) {
      for (int i=0; i &lt; MAX_IP; i+= MAX_IP / threads) {
          HostsLocator detector = new HostsLocator(i, i+(MAX_IP / threads - 1)); // range: from - to
          new Thread(detector).start();                 
      }
  }
  
  public void run() {
      for (int i=from; i&lt;=to; i++)
          findHosts( maskAddress + Integer.toString(i) );
  }
  
  public static boolean findHosts(String IP) {
      InetAddress address = InetAddress.getByName(IP);
      if ( address.isReachable(CONNECTION_TIME_OUT) )
          // host found!
  }
  </code></pre>
  
  <p>However:</p>
  
  <ul>
  <li>With a single thread and a low value in <strong>CONNECTION_TIME_OUT</strong> (500ms) I get wrong <strong>Host Not Found</strong> status for for hosts actually active.</li>
  <li>With a high value in <strong>CONNECTION_TIME_OUT</strong> (5000ms) and only one single thread takes forever to end</li>
  <li>With several threads I've also found problems similar like the first one, due to collisions.</li>
  </ul>
  
  <p>So... I guess there's a better way of solving this problem but I couldn't find it. Any advice? Thanks!</p>