2014-11-06 96 views
0

我想制作一个“通用客户端”,可以连接到任何给定IP地址的服务器。我想知道是否有办法找到端口号。我试过在一段时间内使用for循环(true)。 for循环将终止于65535,即可能的最高端口号。每次它循环通过for循环时,它都会创建一个新的Socket,其中包含正在测试的ip地址和端口号。如何连接到没有java端口号的服务器?

import java.io.IOException; 
import java.net.*; 

public class MainClass { 

static String serverIp = "127.0.0.1"; // or what ever ip the server is on 


public static void main(String[] args) { 

    try { 
     while (true) { 
      for (int x = 1; x == 65535; x++) {     
       Socket serverTest = new Socket(
         InetAddress.getByName(serverIp), x); 
       if(serverTest.isConnected()){ 
        connect(serverTest.getPort()); 
       } 

      } 


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

} 

private static void connect(int port) throws UnknownHostException, IOException { 
    Socket serverTest = new Socket(InetAddress.getByName(serverIp), port);  
} 

}

+0

'isConnected()'测试是徒劳的。如果它没有连接,它就不会被构造:构造函数会抛出某种“IOException”。 – EJP 2014-11-06 23:12:22

+0

我认为这不是一个好方法。如果你在Linux中工作,然后使用一些命令,你可以通过你连接的端口找到 – 2014-11-07 04:55:47

回答

0

我不知道很多关于插口,但我可以告诉你,肯定是你的for循环的一个问题:

for (int x = 1; x == 65535; x++) 

记住,for循环只是扩大像一个while循环,所以这转换为以下内容:

int x = 1; 
while (x == 65535) { 
    // ... 
    x++; 
} 

您现在可以看到发生了什么。 (该循环从未被执行)看起来像你想这样:

//    v 
for (int x = 1; x <= 65535; x++) 
相关问题