[英]How to connect to a server without the port number in java?
I am trying to make a "universal client" that can connect to any server given the IP Address. 我正在尝试制作一个“通用客户端”,该客户端可以连接到给定IP地址的任何服务器。 I was wondering if there is a way to find the port number.
我想知道是否有找到端口号的方法。 I have tried using a for loop inside a while(true).
我试图在while(true)内使用for循环。 The for loop would terminate at 65535, the highest possible port number.
for循环将在65535(可能的最高端口号)处终止。 Each time it would loop through the for loop it would create a new Socket with the ip address and the port number it is testing for.
每次循环通过for循环时,都会使用其IP地址和要测试的端口号创建一个新的Socket。
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);
}
} }
I don't know that much about Socket but I can tell you there is definitely a problem with your for
loop: 我对Socket知之甚少,但是我可以告诉你,
for
循环肯定存在问题:
for (int x = 1; x == 65535; x++)
Remember that a for
loop just expands like a while
loop, so this translates to the following: 请记住,
for
循环只是像while
循环那样展开,因此可以转换为以下内容:
int x = 1;
while (x == 65535) {
// ...
x++;
}
You can probably see what is going on now. 您可能会看到现在发生了什么。 (The loop is never executed.) It seems like you intended this:
(循环永远不会执行。)您似乎打算这样做:
// v
for (int x = 1; x <= 65535; x++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.