我正在尝试将 VB .net 项目从 .net 框架移植到 .net core 和新的 Windows 通用平台应用程序中。
在网络代码中,经常使用.IPAddress.Any,以便能够侦听所有网络适配器。有谁知道 .net core 中我可以使用 DatagramSockets 监听所有网络适配器的方法吗?
IPAddress.Any
相当于 IPAddress ip = IPAddress.Parse("0.0.0.0")
private void Foo()
{
datagramSocket = new DatagramSocket();
datagramSocket.MessageReceived += OnMessageReceived;
await datagramSocket.BindServiceNameAsync("8081");
}
private void OnMessageReceived(
DatagramSocket sender,
DatagramSocketMessageReceivedEventArgs args)
{
// ...
}
private void Foo()
{
Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 8081);
udpSocket.Bind(remoteEndPoint);
SocketAsyncEventArgs e = new SocketAsyncEventArgs();
byte[] buffer = new byte[1024];
e.SetBuffer(buffer, 0, buffer.Length);
e.RemoteEndPoint = remoteEndPoint;
e.Completed += ReceiveFromCallback;
if (!udpSocket.ReceiveFromAsync(e))
{
ReceiveFromCallback(udpSocket, e);
}
}
private void ReceiveFromCallback(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
{
Debug.WriteLine(e.SocketError);
return;
}
Socket udpSocket = sender as Socket;
byte[] buffer = e.Buffer;
Debug.WriteLine(Encoding.UTF8.GetString(buffer, 0, e.BytesTransferred));
if (!udpSocket.ReceiveFromAsync(e))
{
ReceiveFromCallback(udpSocket, e);
}
}
IPAddress.Any = 0.0.0.0 ?????? 我想输入另一台电脑的IP 有什么用 任何IP ??? 我已经搜索了40个网站,它没有解释如何手动输入IP而不是垃圾0.0.0.0