Windows手机的套接字操作遇到了死网

时间:2013-07-11 07:08:44

标签: windows-phone-7 networking windows-phone-8

我正在尝试获取 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 encountered a dead network。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

问题有点陈旧,但回答可能对某人有用:

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