Android 有关Socket的端口占用检测

1,按钮点击事件,执行检测。

    public void play(View view) {
        //定义一个空文本用于储存结果
        String textport = "";
        //定义一个数组用于储存需要检测的端口
        int[] port = {21,22,23,25,69,79,80,88,110,113,119,220,443};

        //循环事件
        for (int i = 0;i < port.length; i++){

            //判断端口是否被占用
            if (isPortAvailable(port[i])){
                textport = textport + "端口 " + port[i] + " 被占用!\n";
            }else{
                textport = textport + "端口 " + port[i] + " 可用!\n";
            }
        }
        //在liebiao中显示检测结果
        TextView tv = (TextView)findViewById(R.id.liebiao);
        tv.setText(textport);
        
    }

2,对端口占用检测的函数。

    private void bindPort(String host,int port)throws Exception{
        //创建一个socket对象
        Socket s = new Socket();
        //对指定端口进行绑定,如果绑定成功则未被占用
        s.bind(new InetSocketAddress(host,port));
        s.close();
    }

    public boolean isPortAvailable(int port){
        try{
            //调用bindport函数对本机指定端口进行验证
            bindPort("0.0.0.0",port);
            bindPort(InetAddress.getLocalHost().getHostAddress(),port);
            return true;
        }catch (Exception e){
            return false;
        }
    }

转载于:https://www.cnblogs.com/Shawna/p/9503518.html

猜你喜欢

转载自blog.csdn.net/weixin_42602900/article/details/131381228