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