更新时间:2023-11-27 13:15:46
创建一个插槽,将检查给定的 IP 特别端口可以连接或不
公共静态布尔isPortOpen(最后弦乐IP,最终诠释口,最终诠释超时){
尝试 {
Socket套接字=新的Socket();
socket.connect(新InetSocketAddress(IP,端口),超时);
socket.close();
返回true;
}
赶上(的ConnectException CE){
ce.printStackTrace();
返回false;
}
赶上(例外前){
ex.printStackTrace();
返回false;
}
}
I am trying to connect to a my remote server from my Android device. How do I check if a specific port on my server is open? Eg. how to check if port 80 is open on my server 11.11.11.11?
Currently, I am using InetAddress
to ping if the host is reachable but this does not tell me if the port 80 is open.
Current Code
boolean isAvailable = false;
try {
isAvailable = InetAddress.getByName("11.11.11.11").isReachable(2000);
if (isAvailable == true) {
//host is reachable
doSomething();
}
} catch (Exception e) {
}
Create a Socket that will check that the given ip with particular port could be connected or not.
public static boolean isPortOpen(final String ip, final int port, final int timeout) {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), timeout);
socket.close();
return true;
}
catch(ConnectException ce){
ce.printStackTrace();
return false;
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
}