PC&IOS&Android 获取局域网IP地址

PC&IOS&Android 获取局域网 IP地址

之前查了挺久的,放上去有时会获取到奇怪的IP,加上Contains(“192.168.”)算是满足一般获取C类 IP地址需求。

  public void GetIp()
    {
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
        if (adapters.Length == 0)
        {
            return;
        }
        //Get in PC.
        foreach (NetworkInterface adapter in adapters)
        {
            NetworkInterfaceType type1 = NetworkInterfaceType.Wireless80211;
            if ((adapter.NetworkInterfaceType == type1) && adapter.OperationalStatus == OperationalStatus.Up)
            {
                Debug.Log("int getIP");

                UnicastIPAddressInformationCollection uniCast = adapter.GetIPProperties().UnicastAddresses;
                if (uniCast.Count > 0)
                {
                    for (var i = 0; i < uniCast.Count; i++)
                    {
                        if (uniCast[i].Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            var getIp = uniCast[i].Address.ToString();
                            Debug.Log("get IP1:" + getIp);
                            if (getIp.Contains("192.168."))//getIp != "127.0.0.1" && getIp.Contains("192.168")
                            {
                                userIp = getIp;
                            }
                        }
                    }
                }
            }
        }
        //Get int IOS or Android.
        if (userIp == "")
        {
            for (int i = 0; i < adapters.Length; i++)
            {
                if (adapters[i].Supports(NetworkInterfaceComponent.IPv4))
                {
                    UnicastIPAddressInformationCollection uniCast = adapters[i].GetIPProperties().UnicastAddresses;
                    if (uniCast.Count > 0)
                    {
                        for (var j = 0; j < uniCast.Count; j++)
                        {
                            //得到IPv4的地址。 AddressFamily.InterNetwork指的是IPv4
                            if (uniCast[j].Address.AddressFamily == AddressFamily.InterNetwork)
                            {
                                var getIp = uniCast[j].Address.ToString();

                                Debug.Log("get Ip2:"+getIp);
                                if (getIp.Contains("192.168."))//getIp != "127.0.0.1" && getIp.Contains("192.168")
                                {
                                    userIp = getIp;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值