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);
}
}
'isConnected()'测试是徒劳的。如果它没有连接,它就不会被构造:构造函数会抛出某种“IOException”。 – EJP 2014-11-06 23:12:22
我认为这不是一个好方法。如果你在Linux中工作,然后使用一些命令,你可以通过你连接的端口找到 – 2014-11-07 04:55:47