用java在远程机器上打开ServerSocket?
我创建了一个简单的方法来尝试确定远程计算机上的套接字是否打开。这是我的代码:
public static Boolean isPortAvailable( int port, String bindAddr ) {
try {
System.out.println("IP: " + InetAddress.getByName(bindAddr ));
ServerSocket srv = new ServerSocket(port, 0, InetAddress.getByName(bindAddr ) );
srv.close();
srv = null;
return true;
} catch (IOException e) {
return false;
}
}
传递这两个参数:
String bindAddr = "remotemachinename";
int port = 1719;
它继续告诉我端口不可用,但如果我在机器上尝试 netstat -a ,我会发现它显然没有在使用中。我错过了什么吗?
I've created a simple method in attempts to determine if a socket is open on a remote machine. Here is my code:
public static Boolean isPortAvailable( int port, String bindAddr ) {
try {
System.out.println("IP: " + InetAddress.getByName(bindAddr ));
ServerSocket srv = new ServerSocket(port, 0, InetAddress.getByName(bindAddr ) );
srv.close();
srv = null;
return true;
} catch (IOException e) {
return false;
}
}
Passing it these two args:
String bindAddr = "remotemachinename";
int port = 1719;
It continues to tell me the port is not available but if I try netstat -a on the machine I see it's clearly NOT in use. Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想联系侦听(服务器)套接字,您应该使用
Socket
而不是ServerSocket
。参见ServerSocket javadoc,第三个参数ServerSocket 构造函数是要绑定的本地地址,而不是要连接的远程地址。试试这个:
If you want to contact a listening (server) socket you should use a
Socket
not aServerSocket
. See the ServerSocket javadoc, the third parameter of the ServerSocket constructor is a local address to bind to, not a remote address to connect to.Try this:
您缺少的是忽略 IOException,这可能告诉您,您不能假装是另一台服务器。我建议您只忽略选择预期异常
按照@fvu建议使用套接字并返回
boolean
而不是Boolean
What you are missing is ignoring your IOException which is probably telling you, you cannot pretend to be another server. I suggest you only ignore select expected exceptions
Use a Socket as @fvu suggests and return a
boolean
not aBoolean