简体   繁体   English

C获取侦听服务器的IP

[英]C Get IP for listening server

I am writing a client/server program using C sockets. 我正在使用C套接字编写客户端/服务器程序。 I am specifying that the server can listen on any network interface by using INADDR_ANY in sockaddr_in.sin_addr.s_addr. 我指定服务器可以通过在sockaddr_in.sin_addr.s_addr中使用INADDR_ANY来侦听任何网络接口。 This is equivalent to an IP of 0.0.0.0. 这相当于IP为0.0.0.0。 Is it possible for me to get the actual IP that the server is listening on? 我可以获得服务器正在监听的实际IP吗? (eg 192.168.1.100) (例如192.168.1.100)

I have finally been able to find a solution that works . 我终于找到了一个有效的解决方案

Edit : link is dead so see: Internet Archive link . 编辑 :链接已死,请参阅: Internet Archive链接

Hopefully it can be helpful to others as it has been to me. 希望它对我来说可能对其他人有所帮助。

When you bind a listening socket to INADDR_ANY , the socket listens on all available local IPs. 将侦听套接字绑定到INADDR_ANY ,套接字将侦听所有可用的本地IP。 There is no way to determine from the socket which IP(s) it is listening on. 无法从套接字确定它正在侦听哪些IP。 If you need that information, then you have to enumerate the local IPs separately (in which case you could just bind() each IP to its own socket individually if you need to retreive pre-accept binding details). 如果您需要该信息,则必须单独枚举本地IP(在这种情况下,如果需要检索预接受绑定详细信息,则可以bind()每个IP单独bind()到其自己的套接字。 However, once accept() has returned an established client connection, you can use getsockname() on the accepted socket to know which specific IP accepted the connection. 但是,一旦accept()返回已建立的客户端连接,您就可以在接受的套接字上使用getsockname()来了解哪个特定的IP接受了该连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM