乐闻世界logo
搜索文章和话题

How to find ports opened by process ID in Linux?

1个答案

1

In Linux systems, finding ports opened by a specific Process ID (PID) can be accomplished through various methods. Below, I will introduce some commonly used approaches:

Method 1: Using the netstat Command

netstat is a powerful networking tool that provides detailed information about network-related statistics, including the ports used by each process in the system. To identify ports opened by a specific process ID, use the following command:

bash
netstat -ltnp | grep '<PID>'

Here, the -l option specifies listening ports, -t indicates TCP ports, -n displays addresses and port numbers in numeric format, and -p shows the process ID and name associated with each connection or listening port. The grep '<PID>' command filters lines containing the specified process ID.

For example, to find ports opened by process ID 1234, execute:

bash
netstat -ltnp | grep '1234'

Method 2: Using the ss Command

The ss command is a modern alternative to netstat for viewing socket information. Similar to netstat, it can be used to locate ports opened by specific processes:

bash
ss -ltnp | grep '<PID>'

The options are consistent with netstat: -l specifies listening ports, -t indicates TCP, -n displays numeric format, and -p shows process details. The grep command filters lines containing the specified process ID.

For instance, to find ports opened by process ID 1234, use:

bash
ss -ltnp | grep '1234'

Method 3: Directly Viewing the /proc File System

The Linux /proc file system contains runtime system information, including details about each process. Each process has a directory named after its PID (e.g., /proc/<PID>), which includes a fd subdirectory listing all file descriptors opened by the process, including network sockets.

To inspect ports for a specific PID, run:

bash
ls -l /proc/<PID>/fd

Then, examine the symbolic links to identify file descriptors of type socket.

Example

For example, to check the port usage of process ID 1234, combine ls and grep:

bash
ls -l /proc/1234/fd | grep socket

This command displays all socket-related file descriptors opened by the process.

The above methods provide several approaches to find ports opened by a specific process ID in Linux. Each method has its own use cases, and you can select the most suitable one based on your requirements.

2024年8月5日 09:59 回复

你的答案