如何替换.Net Core中的System.Net.IPAddress.Any并监听所有网络适配器

问题描述 投票:0回答:2

我正在尝试将 VB .net 项目从 .net 框架移植到 .net core 和新的 Windows 通用平台应用程序中。

在网络代码中,经常使用.IPAddress.Any,以便能够侦听所有网络适配器。有谁知道 .net core 中我可以使用 DatagramSockets 监听所有网络适配器的方法吗?

c# uwp .net-core network-programming
2个回答
2
投票

IPAddress.Any
相当于
IPAddress ip = IPAddress.Parse("0.0.0.0")

使用 Windows.Networking.Sockets.DatagramSocket(Windows 8+)

private void Foo()
{
    datagramSocket = new DatagramSocket();
    datagramSocket.MessageReceived += OnMessageReceived;
    await datagramSocket.BindServiceNameAsync("8081");
}

private void OnMessageReceived(
    DatagramSocket sender,
    DatagramSocketMessageReceivedEventArgs args)
{
    // ...
}

使用 System.Net.Sockets.Socket(.NET Core 和 UWP)

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);
    }
}

0
投票

IPAddress.Any = 0.0.0.0 ?????? 我想输入另一台电脑的IP 有什么用 任何IP ??? 我已经搜索了40个网站,它没有解释如何手动输入IP而不是垃圾0.0.0.0

© www.soinside.com 2019 - 2024. All rights reserved.