本文主要是介绍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 TCP@lsof.itap: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 版本,最后一列就是我们要找的端口号。
这篇关于Linux查看程序占用的端口-lsof的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!