AndroidStudio端口占用檢測


AndroidStudio 3.1.4

1.創建一份新的項目工程,項目名為PortOccupy,界面布局文件名為:activity_port_occupy.xml

2.需要用到2個TextView和1個Button,界面如下

3.Button的鼠標點擊事件函數名為:play

4.用於顯示結果的TextView的ID為liebiao

5.雙擊進入工程代碼撰寫界面

6.代碼如下:

  按鈕按下事件,執行檢測

 1     public void play(View view) {
 2         //定義一個空文本用於儲存結果
 3         String textport = "";
 4         //定義一個數組用於儲存需要檢測的端口
 5         int[] port = {21,22,23,25,69,79,80,88,110,113,119,220,443};
 6 
 7         //循環事件
 8         for (int i = 0;i < port.length; i++){
 9 
10             //判斷端口是否被占用
11             if (isPortAvailable(port[i])){
12                 textport = textport + "端口 " + port[i] + " 被占用!\n";
13             }else{
14                 textport = textport + "端口 " + port[i] + " 可用!\n";
15             }
16         }
17         //在liebiao中顯示檢測結果
18         TextView tv = (TextView)findViewById(R.id.liebiao);
19         tv.setText(textport);
20         }

  對端口占用檢測的函數

    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;
        }
    }

7.最后,就可以調試輸出啦!Lucky~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM