转自:http://blog.csdn.net/begonia__z/article/details/51733101
这几天在弄Ipad的项目,我利用了DNs方法获取Ipad的局域网IP,在PC上并没有什么问题,但是到了Ipad一直都连不上服务器这里,然后就把IP打印出来,发现IP地址不对的说,DNs好像获取到的是别的IP地址。
然后我上网查了一下资料找到新的方法,代码如下:(PS:我顺便把Dns的代码一起放出来,第一个方法好像在PC上也适用,但是安卓和其他平台我没有去发布)
/// <summary>
/// 获取局域网的IP
/// </summary>
/// <returns></returns>
public string GetAddressIP()
{
string AddressIP = string.Empty;
#if UNITY_IPHONE
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); ;
foreach (NetworkInterface adapter in adapters)
{
if (adapter.Supports(NetworkInterfaceComponent.IPv4))
{
UnicastIPAddressInformationCollection uniCast = adapter.GetIPProperties().UnicastAddresses;
if (uniCast.Count > 0)
{
foreach (UnicastIPAddressInformation uni in uniCast)
{
//得到IPv4的地址。 AddressFamily.InterNetwork指的是IPv4
if (uni.Address.AddressFamily == AddressFamily.InterNetwork)
{
AddressIP = uni.Address.ToString();
}
}
}
}
}
#endif
#if UNITY_STANDALONE_WIN
///获取本地的IP地址
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = _IPAddress.ToString();
}
}
#endif
return AddressIP;
}
记得自己引入using System.Net.NetworkInformation;不然代码是会有错误的
给大家提个醒在项目的编程中尽量别使用foreach,如果想知道为什么直接去百度和谷歌去。
/// <summary>
/// <span style="font-family: Arial, Helvetica, sans-serif;">获取局域网的IP</span>
/// </summary>
/// <returns></returns>
public string GetAddressIP()
{
string AddressIP = string.Empty;
#if UNITY_IPHONE
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
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 (int j = 0; j < uniCast.Count; j++)
{
//得到IPv4的地址。 AddressFamily.InterNetwork指的是IPv4
if (uniCast[j].Address.AddressFamily == AddressFamily.InterNetwork)
{
AddressIP = uniCast[j].Address.ToString();
}
}
}
}
}
#endif
#if UNITY_STANDALONE_WIN || UNITY_ANDROID
///获取本地的IP地址
for (int i = 0; i < Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length; i++)
{
if (Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].AddressFamily.ToString() == "InterNetwork")
{
AddressIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].ToString();
}
}
//foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
//{
// if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
// {
// AddressIP = _IPAddress.ToString();
// }
//}
#endif
return AddressIP;
}
网友评论