1

我正在尝试获取Wi-Fi、数据网络等网络的 IP 地址。我使用以下来查找IP。

public class MyIPAddress
{
    Action<IPAddress> FoundCallback;
    UdpAnySourceMulticastClient MulticastSocket;
    const int PortNumber = 50000;       // pick a number, any number
    string MulticastMessage = "FIND-MY-IP-PLEASE" + new Random().Next().ToString();

    public void Find(Action<IPAddress> callback)
    {
        FoundCallback = callback;

        MulticastSocket = new UdpAnySourceMulticastClient(IPAddress.Parse("239.255.255.250"), PortNumber);
        MulticastSocket.BeginJoinGroup((result) =>
        {
            try
            {
                MulticastSocket.EndJoinGroup(result);
                GroupJoined(result);
            }
            catch (Exception ex)
            {
                //  Debug.WriteLine("EndjoinGroup exception {0}", ex.Message);
                // This can happen eg when wifi is off
                FoundCallback(null);
            }
        },
            null);
    }

    void callback_send(IAsyncResult result)
    {
    }

    byte[] MulticastData;
    bool keepsearching;

    void GroupJoined(IAsyncResult result)
    {
        MulticastData = Encoding.UTF8.GetBytes(MulticastMessage);
        keepsearching = true;
        MulticastSocket.BeginSendToGroup(MulticastData, 0, MulticastData.Length, callback_send, null);

        while (keepsearching)
        {
            try
            {
                byte[] buffer = new byte[MulticastData.Length];
                MulticastSocket.BeginReceiveFromGroup(buffer, 0, buffer.Length, DoneReceiveFromGroup, buffer);
            }
            catch (Exception ex)
            {
                // Debug.WriteLine("Stopped Group read due to " + ex.Message);
                keepsearching = false;
            }
        }
    }

    void DoneReceiveFromGroup(IAsyncResult result)
    {
        string str = "";
        IPEndPoint where;
        int responselength = MulticastSocket.EndReceiveFromGroup(result, out where);
        byte[] buffer = result.AsyncState as byte[];
        if (responselength == MulticastData.Length && buffer.SequenceEqual(MulticastData))
        {
            str = where.Address.ToString();
            keepsearching = false;
            FoundCallback(where.Address);
        }

        Console.WriteLine(str);

    }
}

我成功找到了连接的Wi-Fi的 IP 地址。我关闭 Wi-Fi 并打开数据连接。我无法获取已连接网络的 IP 地址。我收到错误**套接字操作遇到死网络**。我也参考了这个问题A socket operation遇到了死网。我怎么解决这个问题 ?

4

1 回答 1

1

问题有点老了,但答案可能对某人有用:

您会收到此错误,因为您的MyIPAddress类只能找到一个本地 IP(您的内部 WiFi 网络中的地址,位于路由器后面)。要获取外部 IP地址,您应该调用一个外部服务器,它会告诉您您的 IP(例如 whatismyip.com)。

于 2014-01-30T19:26:54.427 回答