Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an IP address and a port number together uniquely identify a process ID?

Tags:

c++

c

tcp

sockets

udp

Can an IP address and a port number together uniquely identify a process ID?

I'm looking for a way to get the corresponding process ID, given an IP address and a port number, but I'm not sure whether such ip/port pairs can uniquely identify one pid.

like image 319
flyingbin Avatar asked Dec 10 '22 03:12

flyingbin


2 Answers

Not necessarily. If a socket is opened/accepted in a process, and it then forks, the child process also has the socket open, so the IP address and port number are used by two processes.

like image 103
Jonathan Leffler Avatar answered Dec 11 '22 17:12

Jonathan Leffler


As Jonathan pointed out, the relation is not necessarily unique. For instance, there are server implementations (apache/prefork) which use child processes to handle requests concurrently.

But you can get the list of processes using a specific port/address anyway (although there might be multiple entries for a single port/address pair), perhaps in your specific case this is a viable solution:

In Windows, for example, you can use the GetExtendedTcpTable function, setting the TableClass parameter to one of the TCP_TABLE_OWNER_MODULE_* values. This returns a table containing local and remote address/port and process ID for all current TCP endpoints.

On Linux there are certainly similar ways (although I do not know by heart how to do it...), since this is exactly what the netstat -p program does.

like image 36
MartinStettner Avatar answered Dec 11 '22 15:12

MartinStettner