除了在 Linux 的主機外, 在其他類型的主機也經常需要檢查埠號是否有開啟埠號, 例如要測試主機的服務是否正常。
以下是分別用 nc, nmap 及 telnet 測試埠號是否有開啟的方法。
nc (netcat)
nc 的意思是 netcat, nc 可以讀取經過 TCP 及 UDP 的網路連線資料, 是一套很實用的網路除錯工具。
在 CentOS 用 yum 安裝 nc:
- # yum install nc
如果只是單純檢查埠號是否有開啟, 可以用以下指令, 以下指令會測試 192.168.1.10 的 port 80 是否開啟:
- $ nc -zvw3 192.168.1.10 80
如果埠號有開啟, 會回傳類似以下內容:
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to 192.168.1.10:80.
Ncat: 0 bytes sent, 0 bytes received in 0.01 seconds.
Ncat: Connected to 192.168.1.10:80.
Ncat: 0 bytes sent, 0 bytes received in 0.01 seconds.
如果沒有開啟, 會回傳以下內容:
Ncat: No route to host.
nmap
nmap (Network Mapper) 是另一個可以檢查埠號的工具, 檢查語法是這樣:
在 CentOS 用 yum 安裝 nmap:
- # yum install nmap
用 nmap 檢查 port 80 是否開啟:
- $ nmap 192.168.1.10 -p 80
如果埠號有開啟, 會回傳以下內容:
Starting Nmap 6.40 ( http://nmap.org ) at 2019-03-27 15:42 HKT
Nmap scan report for 192.168.1.10
Host is up (0.00042s latency).
PORT STATE SERVICE
80/tcp open http
Nmap scan report for 192.168.1.10
Host is up (0.00042s latency).
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 0.04 seconds
如果沒有開啟, 會有以下輸出:
Starting Nmap 6.40 ( http://nmap.org ) at 2019-03-27 15:45 HKT
Nmap scan report for 192.168.1.10
Host is up (0.00045s latency).
PORT STATE SERVICE
80/tcp filtered http
Nmap scan report for 192.168.1.10
Host is up (0.00045s latency).
PORT STATE SERVICE
80/tcp filtered http
Nmap done: 1 IP address (1 host up) scanned in 0.04 seconds
Telnet
Telnet 是另一個可以檢查埠號的工具.
在 CentOS 用 yum 安裝 Telnet:
- # yum install telnet
用 Telnet 檢查 port 80 是否開啟:
- $ telnet 192.168.1.10 80
如果埠號有開啟, 會有以下輸出:
Trying 192.168.1.10…
Connected to 192.168.1.10.
Escape character is ‘^]’.
^CConnection closed by foreign host.
Connected to 192.168.1.10.
Escape character is ‘^]’.
^CConnection closed by foreign host.
要離開 Telnet 按 “Ctrl + C” 鍵.
如果埠號沒有開啟, 會出現以下結果:
$ telnet 192.168.1.10 80
Trying 192.168.1.10…
telnet: Unable to connect to remote host: Connection refused
Trying 192.168.1.10…
telnet: Unable to connect to remote host: Connection refused