如何知道TCP连接是否在同一台机器上的两个进程之间?
使用套接字编程 API(例如,socket()、connect()、accept() ...),我如何知道 TCP 连接是否位于同一台机器上的两个进程之间?比如说,我有套接字文件描述符和远程 IP。我可以简单地检查远程IP是否为127.0.0.1吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有真正可靠的方法来确定这一点 - 您可以使用全局路由的 IP 地址连接到本地进程(即本地进程可以使用
127.0.0.1
之外的 IP)。如果您处于虚拟化环境中,进程也可以在同一物理硬件上的不同虚拟机中运行。但请注意,如果远程 IP(通过
getpeername
)或本地 IP(通过getsockname
)以127
开头(包括127.0 .0.1
),那么它确实是本地连接;但是,如果是不同的地址对,则不能排除它可能是本地连接的可能性。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 (viagetsockname
) starts with127
(including127.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.使用
getsockname()
和getpeername()
检索与连接关联的两个 IP,然后使用gethostname()
和gethostbyname( )
(或其他特定于平台的 API,例如 Windows 上的GetAdaptersInfo()
和GetAdapterAddresses()
)来确定属于本地计算机的 IP,然后您可以将连接 IP 与本地计算机 IP 进行比较,看看它们是否都匹配。一台机器可以分配多个IP,同一台机器上的多个IP可以互相通信。Use
getsockname()
andgetpeername()
to retreive the two IPs associated with the connection, then usegethostname()
andgethostbyname()
(or other platform-specific APIs, likeGetAdaptersInfo()
andGetAdapterAddresses()
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.这是我使用的方法。这个想法是尝试将侦听器绑定到该 IP 地址,并使用失败/成功代码来确定该地址是否是本地地址。
我并不是说这特别有效,但它应该相当可靠,并且对于我的应用程序来说它是合适的。
你这样称呼它:
Here is the approach I have used. The idea is to attempt to bind a listener to that IP address and use the failure/success codes to decide whether the address is local.
I am not claiming this is particularly efficient, but it should be fairly reliable, and for my application it was appropriate.
You call it like this:
如果你已经有了远程IP地址,你可以检查它是否是环回地址或者是否是主机的IP地址,因为,正如cnicutar指出的那样,它不必通过环回地址来成为一个本地连接。
If you already have the remote ip address, you can check if it is the loopback address or if it is the ip address of the host, because, as cnicutar points out, it doesn't have to be over the loopback address to be a local connection.