2016-04-04 121 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