问题描述
我正在尝试获取绑定到receiveSock的IP地址.我怎么得到它.
I am trying to get an ip address that is bound to receiveSock. How can i get it.
问题1:
ipEndReceive = new IPEndPoint(IPAddress.Any, receivePort);
receiveSock = new Socket(AddressFamily.InterNetwork
, SocketType.Stream, ProtocolType.Tcp);
receiveSock.Bind(ipEndReceive);
代码到达绑定功能时.发生错误
When code reaches Bind function. An error occurs
问题2:
ipEndReceive = new IPEndPoint(IPAddress.Parse("127.0.0.1"), receivePort);
receiveSock = new Socket(AddressFamily.InterNetwork
, SocketType.Stream, ProtocolType.Tcp);
receiveSock.Bind(ipEndReceive);
ErrorLog.WritetoErrorlog("\nRemote IP Address : " + ((IPEndPoint)receiveSock.RemoteEndPoint).Address.ToString()
当我尝试使用该IP时.它显示出与上述相同的错误
When I tries with this Ip. It shows me the same error as above
推荐答案
首先,它看起来像是您想要的本地端点.其次,当您指定IPAddress.Any
(0.0.0.0
)时,您明确声明Socket
将不绑定到任何特定接口.每个IP地址都完全匹配一个接口.
First, it looks like it's the local end point you want. Secondly when you specify IPAddress.Any
(0.0.0.0
) you explicitly state that the Socket
is to be bound to no particular interface. Each IP adress matches exactly one interface.
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, somePort));
Trace.WriteLine(s.LocalEndPoint); // should be what you're looking for
套接字已绑定,将用于接收连接.它没有RemoteEndPoint
.这很清楚,因为Accept
方法返回一个新的Socket
对象,该对象表示两个端点(本地/远程)之间的连接.
The socket is bound and will be used for receiving connections. It doesn't have a RemoteEndPoint
. This should be abundantly clear becuase the Accept
method returns a new Socket
object that represents the connection between two end points (local/remote).
注意:这是一个IPv4套接字(AddressFamily.InterNetwork
),因此请勿尝试将其绑定到其他任何东西.
Note: that this is an IPv4 socket (AddressFamily.InterNetwork
) so don't try and bind it to anything else.
在 MSDN ,您可以在那里了解更多有关典型Winsock编程的信息(因为Socket类只是Winsock的包装器).
Check out the docs on MSDN, you can learn more about typical Winsock programming (as the Socket class is just a Winsock wrapper) there.
这篇关于如何从套接字获取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!