2014-06-06 102 views
0

我想在我的網絡中查找我的服務器,當時我不知道該IP。 所以這是我的代碼,但它需要很長的測試所有IP(!):Java - 在網絡中查找服務器

for (int j = 1; j < 255; j++) { 
    for (int i = 1; i < 255; i++) { 
     String iIPv4 = "192.168." + j + "."; 
     try { 
      Socket socket = new Socket(); 
      SocketAddress address = new InetSocketAddress(iIPv4 + i, 2652); 
      socket.connect(address, 5); 
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
      String fromServer; 
      while ((fromServer = in.readLine()) != null) { 
      if (fromServer.equals("Connected to CC3000")) { 
       System.out.println("CC3000 found! : " + iIPv4 + i); 
       return iIPv4 + i; 
      } 
      } 
     } catch (UnknownHostException e) { 
     } catch (IOException e) { 
     } 
    } 
} 

所以,什麼更好的方法來查找服務器?

問候

+0

如果您知道服務器的主機名和域,可以直接使用它。 –

+0

這將需要很長時間!您正試圖對每個主機執行TCP連接。讓服務器監聽廣播/多播數據包並做出響應(假設本地局域網 - 類似於UPnP的工作原理),怎麼辦?失敗的DNS? – chrixm

+0

@RomanC我知道,但我想讓它變得動態。 – maysi

回答

0

我認爲多線程可以幫助你在這裏,因爲你不想在等待每個連接要麼建立或失敗。

你可以嘗試一次說數百個套接字。同時檢查IP是否可達可能會爲您節省一些時間。

下面的代碼實際上是一個天真和可怕的例子,因爲根本沒有線程管理,但你得到了我希望的圖片。你應該更快地得到結果。

public static void findLanSocket(final int port, final int timeout) { 
    List<Thread> pool = new ArrayList<>(); 

    for (int j = 1; j < 255; j++) { 
     for (int i = 1; i < 255; i++) { 
      final String iIPv4 = "192.168." + j + "." + i; 

      Thread thread = new Thread(new Runnable() { 

       @Override 
       public void run() { 
        System.out.println("TESTING: " + iIPv4); 

        try { 
         // First check if IP is reachable at all. 
         InetAddress ip = InetAddress.getByName(iIPv4); 
         if (!ip.isReachable(timeout)) { 
          return; 
         } 

         // Address is reachable -> try connecting to socket. 
         Socket socket = new Socket(); 
         SocketAddress address = new InetSocketAddress(ip, port); 
         socket.connect(address, timeout); 

         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
         String fromServer; 
         while ((fromServer = in.readLine()) != null) { 
          if (fromServer.equals("Connected to CC3000")) { 
           System.out.println("CC3000 found! : " + iIPv4); 
          } 
         } 

        } catch (UnknownHostException e) { 
        } catch (IOException e) { 
        } 
       } 
      }); 

      pool.add(thread); 
      thread.start(); 
     } 
    } 

    // Wait for threads to die. 
    for (Thread thread : pool) { 
     try { 
      if (thread.isAlive()) { 
       thread.join(); 
      } 
     } catch (InterruptedException ex) { 
     } 
    } 
}