Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a TCP connection is between two processes on the same machine?

Tags:

c++

c

tcp

sockets

Using socket programming APIs (e.g., socket(), connect(), accept() ...), how can I know if a TCP connection is between two processes on the same machine? Say, I have the socket file descriptor, and the remote ip. Can I simply inspect if the remote ip is 127.0.0.1?

like image 941
flyingbin Avatar asked Jan 03 '12 21:01

flyingbin


2 Answers

There's no really reliable way to determine this - you can connect to local processes using a globally routed IP address (ie, local processes can use IPs other than 127.0.0.1). It's also possible for a process to run in a different virtual machine on the same physical hardware, if you're in a virtualized environment.

Note, however, that if the remote IP (via getpeername) or local IP (via getsockname) starts with 127 (including 127.0.0.1), then it is indeed a local connection; however, you can't rule out the possibility that it might be a local connection if it's a different pair of addresses.

like image 177
bdonlan Avatar answered Oct 11 '22 05:10

bdonlan


Use getsockname() and getpeername() to retreive the two IPs associated with the connection, then use gethostname() and gethostbyname() (or other platform-specific APIs, like GetAdaptersInfo() and GetAdapterAddresses() on Windows) to determine the IPs that belong to the local machine, then you can compare the connection IPs to the local machine IPs to see if they both match. A machine can have multiple IPs assigned to it, and multiple IPs on the same machine can communicate with each other.

like image 34
Remy Lebeau Avatar answered Oct 11 '22 04:10

Remy Lebeau