在unity 脚本中获取客户端的IP地址

需要using System.Net.NetworkInformation;
原理就是获取网卡的信息。

//下面这段代码是我在百度贴吧找来的,经检验是正确的

string userIp = "";
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)
        {
          userIp =uni.Address.ToString();
        }
      }
    }
  }
}

在unity 脚本中获取客户端的IP地址_第1张图片

你可能感兴趣的:(unity)