如果服务器端口检查是Android开放 [英] Checking if server port is open from Android

查看:769
本文介绍了如果服务器端口检查是Android开放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的Andr​​oid设备连接到我的远程服务器。如何检查我的服务器上的特定端口是开放的?例如。如何检查80端口是打开我的服务器上11.11.11.11?

目前,我使用的InetAddress 来ping主机是否可达,但这并没有告诉我,如果80端口是开放的。

目前的code

 布尔isAvailable = FALSE;
尝试 {
    isAvailable = InetAddress.getByName(11.11.11.11)isReachable(2000);
    如果(isAvailable ==真){
       //主机是否可达
       做一点事();
    }
}赶上(例外五){

}
 

解决方案

创建一个插槽,将检查给定的 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;
        }
    }

这篇关于如果服务器端口检查是Android开放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆