2016-04-04 124 views
-2

我試圖實現一個線程連續ping局域網連接。我想通過爲每個IP創建新的Socket來做到這一點,而如果它無法連接則處理異常。然而,執行序列超時創建套接字(我用代碼中的註釋對其進行了簽名)。Java多線程,套接字

我該如何解決這個問題?

class Ping implements Runnable 
{ 

    private int actPort = 1024; 

    public void run() 
    {   
     Socket s; 
     int[] ip = {192,168,0,0}; 

     while(true){ 

      try { 

       for(int i = 0;i<256;i++) 
       { 
        ip[2] = i; 

        for(int j = 0;j<256;j++) 
        { 

         ip[3] = j; 
         String address = ip[0]+"."+ip[1]+"."+ip[2]+"."+ip[3]; 
         s = new Socket(address,actPort); // EXECUTION STOPS 
         System.out.println(address);        
        } 
       }     

      } catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 

     } 

    } 
} 

感謝您的時間

+0

做它的時候了最後? –

+0

不,對不起,我編輯的問題。 – freestar

+0

所以爲什麼你認爲它不會超時,如果IP地址不存在? –

回答

1

你正在創建Socket,這是一個TCP/IP數據流,並創建你(客戶端)並給予IPPORT之間有狀態的連接。 我假設,這個程序在創建第一個Socket時停止。

如果你看一下Socket類的API:

* If UDP socket is used, TCP/IP related socket options will not apply. 
* 
* @param  host  the IP address. 
* @param  port  the port number. 
* @param  stream if {@code true}, create a stream socket; 
*      otherwise, create a datagram socket. 
@Deprecated 
public Socket(InetAddress host, int port, boolean stream) throws IOException { 
    this(host != null ? new InetSocketAddress(host, port) : null, 
     new InetSocketAddress(0), stream); 
} 

這是@Deprecated版本創建UDP套接字,但你真正需要的是從java.net,創建無狀態的連接DatagramPacket,並可超時如果數據包沒有走到盡頭。

看看這裏寫DatagramPacket的一些示例代碼:

https://github.com/awadalaa/Socket-Programming-Java/blob/master/UDP-Pinger/PingClient.java

1

你正在嘗試做既是IP掃描儀(環上的所有192.168)和端口掃描儀。所以,你可以爲這兩個搜索解決方案: java code to ping an IP address Sockets: Discover port availability using Java

對於多線程的一部分,它使65536值來測試,這將使線程太多,所以你可以使用與執行人一個線程池,並取消它,如果它需要太長。

看到使用的方法(我讓你做的算法

tp = Executors.newWorkStealingPool(512); // to create up to 512 Threads 
//todo the creation loop... 
future = tp.submit(()->{/* your port scan */ return true;}); 
//todo the waiting processing 
future.cancel(true);// to cancel your future