Open ServerSocket on remote machine with java?
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?
If you want to contact a listening (server) socket you should use a Socket
not a ServerSocket
. 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:
try {
InetAddress addr = InetAddress.getByName(bindAddr);
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress(addr, port);
int timeout = 1000; // wait for 1 second = 1000ms (adapt to your use case)
sock.connect(sockaddr, timeout);
} catch (UnknownHostException e) {
} catch (SocketTimeoutException e) {
// nobody's listening or willing to accept our connection...
} catch (IOException e) {
}
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 a Boolean
精彩评论