【案例分析】Linux下怎样查看port占用情况

时间:2023-03-09 03:30:36
【案例分析】Linux下怎样查看port占用情况
  作者:zhanhailiang 日期:2014-11-08

基于express写一个測试server代码例如以下,可是执行失败,报“listen EADDRINUSE”。字面上理解是error address in use,说明当前你监听的port3000已经被使用了:

[root@~/wade/wadetest]# cat index.js
var express = require('express');
var app = express();
 
app.get('/', function(req, res){
res.send('hello world');
});
 
app.listen(3000, function() {
 
});
[root@~/wade/wadetest]# node index.js
 
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at EventEmitter.app.listen (/root/wade/wadetest/node_modules/express/lib/application.js:559:24)
at Object.<anonymous> (/root/wade/wadetest/index.js:8:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)

尝试使用netstat查看当前机器port占用情况:

[root@~]# netstat -anop
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name Timer
tcp 0 0 0.0.0.0:6379 0.0.0.0:* LISTEN 5906/redis-server * off (0.00/0/0)
tcp 0 0 127.0.0.1:11211 0.0.0.0:* LISTEN 8023/memcached off (0.00/0/0)
tcp 0 0 0.0.0.0:6380 0.0.0.0:* LISTEN 26815/redis-server off (0.00/0/0)
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 2720/nginx off (0.00/0/0)
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 23854/sshd off (0.00/0/0)
tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN 6732/node off (0.00/0/0)
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 2466/php-fpm off (0.00/0/0)
tcp 0 0 0.0.0.0:3690 0.0.0.0:* LISTEN 25447/svnserve off (0.00/0/0)
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 23376/mysqld off (0.00/0/0)

当中:

-n, --numeric              don't resolve names
-p, --programs display PID/Program name for sockets
-a, --all, --listening display all sockets (default: connected)
-o, --timers display timers

由上可见。port3000被PID为6732的node进程占用。

接下来通过ps查询该进程的具体信息:

[root@~]# ps -f -p 6732
UID PID PPID C STIME TTY TIME CMD
root 6732 6703 0 Nov02 ? 00:00:00 node /root/wade/git/node-lessons/lesson1/app.js
[root@~/wade/wadetest]# ps -fp 6703
UID PID PPID C STIME TTY TIME CMD
root 6703 1 0 Nov02 ? 00:00:00 pm2: Daemon

当中:

-f full 表示输出进程完整信息,如上所看到的
-p by process ID 表示查询指定进程ID

最后。kill掉进程6703或停止pm2服务就可以正常执行上面的node演示样例:

[root@~/wade/git/node-lessons/lesson1]# pm2 kill
[PM2] Stopping PM2...
[PM2] Deleting all process
[PM2] deleteProcessId process id 0
[PM2] All processes has been stopped and deleted
[PM2] PM2 stopped
[root@~/wade/wadetest]# node index.js

例如以下图:

【案例分析】Linux下怎样查看port占用情况

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYmlsbGZlbGxlcg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">