在linux相关设备上经常会需要判断“进程打开了哪些端口,某端口是哪个进程打开的”相关信息,下面来看下如何获取这些信息。
注:"进程打开了哪些端口"与“某个端口属于哪个进程/线程”信息收集过程相近,只看“某个端口属于哪个进程/线程”情况。通过我们会直接通过netstat -tunlp这个命令搞定,但是嵌入式设备上却不支持-p选项。
1.netstat查看端口
嵌入式设备上netstat命令不支持-p,无法定位到端口所属进程
# busybox netstat -atnp
netstat: invalid option -- 'p'
BusyBox v1.27.2 (2018-10-09 14:13:48 CST) multi-call binary.
Usage: netstat [-ral] [-tuwx] [-en]
Display networking information
-r Routing table
-a All sockets
-l Listening sockets
Else: connected sockets
-t TCP sockets
-u UDP sockets
-w Raw sockets
-x Unix sockets
Else: all socket types
-e Other/more information
-n Don't resolve names
在嵌入式设备上运行netstat命令,查询开启端口信息:
# busybox netstat -atne
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN
tcp 0 0 172.16.42.197:49494 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp 0 0 172.16.42.197:40615 180.149.144.101:443 ESTABLISHED
tcp 0 208 172.16.42.197:22 172.16.42.178:54688 ESTABLISHED
tcp 0 0 172.16.42.197:40770 101.201.176.18:443 ESTABLISHED
tcp 32 0 172.16.42.197:55982 119.75.222.168:443 CLOSE_WAIT
tcp 32 0 172.16.42.197:40950 123.125.115.234:443 CLOSE_WAIT
tcp 0 0 172.16.42.197:51078 220.181.164.157:443 ESTABLISHED
tcp 32 0 172.16.42.197:40954 123.125.115.234:443 CLOSE_WAIT
netstat: /proc/net/tcp6: No such file or directory
2.如何通过端口号定位到进程pid
- 利用 /proc/net/tcp、/proc/net/tcp6、/proc/net/udp、/proc/net/udp6来通过端口号查找socket对应的inode节点:
比如我们要查找49494端口所属进程:49494转化成16进制就是:C156
# cat /proc/net/tcp
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 0100007F:0035 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 1104 1 ffffffc005db8000 100 0 0 10 0
1: C52A10AC:C156 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 32878 1 ffffffc003da2d00 100 0 0 10 0
2: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 1143 1 ffffffc005db8780 100 0 0 10 0
3: C52A10AC:9EA7 659095B4:01BB 01 00000000:00000000 00:00000000 00000000 0 0 566441 1 ffffffc003da2580 21 4 28 10 -1
4: C52A10AC:0016 B22A10AC:D5A0 01 00000028:00000000 01:00000014 00000000 0 0 935471 4 ffffffc005dbc380 21 4 23 10 26
5: C52A10AC:9F42 12B0C965:01BB 01 00000000:00000000 00:00000000 00000000 0 0 944582 1 ffffffc005f25a00 22 4 28 10 -1
6: C52A10AC:9FF6 EA737D7B:01BB 08 00000000:00000020 00:00000000 00000000 0 0 565897 1 ffffffc005e1da00 20 4 28 10 -1