記得以前在寫程序的時候,有一次需要查看端口的被占用情況,雖然我不會,但是有人會。所以通過網(wǎng)上查找相關(guān)的文章,具體如下。
127.0.0.1代表本機
主要原理是:
1
|
|
如果對該主機的特定端口號能建立一個socket,則說明該主機的該端口在使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
/** * @author MrBread * @date 2017年6月18日 * @time 下午3:14:05 * @project_name TestSocket * 功能:檢測本機端口是否已經(jīng)被使用用 */ package com.mycode.www; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class Main { //start--end是所要檢測的端口范圍 static int start= 0 ; static int end= 1024 ; public static void main(String args[]){ for ( int i=start;i<=end;i++){ System.out.println( "查看" +i); if (isLocalPortUsing(i)){ System.out.println( "端口 " +i+ " 已被使用" ); } } } /** * 測試本機端口是否被使用 * @param port * @return */ public static boolean isLocalPortUsing( int port){ boolean flag = true ; try { //如果該端口還在使用則返回true,否則返回false,127.0.0.1代表本機 flag = isPortUsing( "127.0.0.1" , port); } catch (Exception e) { } return flag; } /*** * 測試主機Host的port端口是否被使用 * @param host * @param port * @throws UnknownHostException */ public static boolean isPortUsing(String host, int port) throws UnknownHostException{ boolean flag = false ; InetAddress Address = InetAddress.getByName(host); try { Socket socket = new Socket(Address,port); //建立一個Socket連接 flag = true ; } catch (IOException e) { } return flag; } } |
輸出結(jié)果如下:
1
2
3
4
5
6
7
8
9
|
查看 0 查看 1 查看 2 查看 3 查看 4 查看 5 查看 6 查看 7 查看 8 |
以上就是本文關(guān)于如何查看端口是否被占用的實例源碼,希望對大家有所幫助。
原文鏈接:http://blog.csdn.net/lcr_happy/article/details/73433508