Linux查看程序佔用的端口-lsof

在作網絡編程時,我們經常要知道程序打開的端口號。這裏介紹一種簡單的端口號查詢命令-lsof和具體方法:
首先,介紹一下 losf 命令。使用 “man lsof” 查看lsof的幫助文檔。這裏截取一部分:

NAME
lsof - list open files
DESCRIPTION
Lsof revision 4.87 lists on its standard output file information about files opened by processes
An open file may be a regular file, a directory, a block special file, a character special file, an executing text reference, a library, a stream or a network file (Internet socket, NFS file or UNIX domain socket.) A specific file or all the files in a file system may be selected by path.
Instead of a formatted display, lsof will produce output that can be parsed by other programs. See the -F, option description, and the OUTPUT FOR OTHER PROGRAMS section for more information.

描述的大意:lsof 用於列舉進程打開文件文件情況,這裏的的文件包括普通文件,目錄,塊設備,字符設備,可執行文件,庫,流,以及網絡文件(如 套接字),這裏體現了 UNIX 系統的主要哲學—萬物皆文件,並且該命令的輸出可以作爲其他命令的輸入。
瞭解 lsof 命令的大意後,我們重點了解該命令選項“-i”:
-i select IPv[46] files
i 選項用於選擇打開的 IPv 文件,選項參數:
[46][protocol][@hostname|hostaddr][:service|port]
其中
46 指定 IP 版本,4指 IPv4,6指 IPv6,使用時如果都不指定則匹配時二者都選擇。
protocol 指定協議名稱,包括 TCP, UDP
hostname 指定網絡主機名
hostaddr 主機 IP地址
service/etc/services中出現的服務名 或者服務列表,如 smtp
port 匹配的端口號,亦可以是一個範圍

使用時,上述參數必須至少指定一個。’@‘在指定主機名時不可省略,’:‘在指定端口或服務時也不可省略。服務名和端口號列表可以用’-‘連接表示範圍,之用’,‘隔開。

At least one address component - 4, 6, protocol, hostname, hostaddr, or service - must be supplied. The ‘@’ character, leading the host specification, is always required; as is the ‘:’, leading the port specification. Specify either hostname or hostaddr. Specify either service name list or port number list. If a service name list is specified, the protocol may also need to be specified if the TCP, UDP and UDPLITE port numbers for the service name are different. Use any case - lower or upper - for protocol. Service names and port numbers may be combined in a list whose entries are separated by commas and whose numeric range entries are separated by minus signs. There may be no embedded spaces, and all service names must belong to the specified protocol. Since service names may contain embedded minus signs, the starting entry of a range can’t be a service name; it can be a port number, however.

舉例:
lsof -i6 #IPv6 only
losf -i TCP:25 #TCP and port 25
losf -i @1.2.3.4 #Internet IPv4 host address 1.2.3.4
losf -i @[3ffe:1ebc::1]:1234 #Internet IPv6 host address 3ffe:1ebc::1, port 1234
losf -i UDP:who #UDP who service port
losf -i [email protected]:513 #TCP, port 513 and host name lsof.itap
losf -i tcp@foo:1-10,smtp,99 #TCP, ports 1 through 10, service name smtp, port 99, host name foo
losf -i tcp@bar:1-smtp #TCP, ports 1 through smtp, host bar

然而,當我們要查詢程序打開的端口號時,可以用如下命令查看:
cherry@localhost libevent$ lsof -i | grep -i "server3" | grep -v grep
server3   1026 cherry    3u  IPv4 0x60f998b5c292148f      0t0  TCP *:5778 (LISTEN)

查找結果列出了程序名,PID,屬主用戶, IP 版本,最後一列就是我們要找的端口號。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章