如何在Unity 2018+中获取设备的IP地址? [英] How to get IP address of device in Unity 2018+?
问题描述
如何在Unity 2018.2+中为Android设备开发的程序中获取C#上的IP地址?
How to get IP address on C# in program which developing for android device in Unity 2018.2+?
似乎已不推荐使用Network.player.ipAddress
,所以我正在寻找一种新方法.
Seems like Network.player.ipAddress
is deprecated right now, so I'm looking for a new way.
推荐答案
Network.player.ipAddress
已被弃用,因为它基于旧的过时的Unity网络系统.
The Network.player.ipAddress
has been deprecated since it is based on the old obsolete Unity networking system.
如果您正在使用Unity的新uNet网络系统,则可以使用 NetworkManager.networkAddress
;
If you are using Unity's new uNet Network System, you can use NetworkManager.networkAddress
;
string IP = NetworkManager.singleton.networkAddress;
如果使用的是原始网络协议和TCP/UDP等API,则必须使用NetworkInterface
API查找IP地址.我使用的IPManager
在台式机和移动设备上一直为我服务:
If you are using raw networking protocol and APIs like TCP/UDP, you have to use the NetworkInterface
API to find the IP Address. I use IPManager
which has been working for me on both desktop and mobile devices:
IPv4 :
string ipv4 = IPManager.GetIP(ADDRESSFAM.IPv4);
IPv6 :
string ipv6 = IPManager.GetIP(ADDRESSFAM.IPv6);
IPManager
类:
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
public class IPManager
{
public static string GetIP(ADDRESSFAM Addfam)
{
//Return null if ADDRESSFAM is Ipv6 but Os does not support it
if (Addfam == ADDRESSFAM.IPv6 && !Socket.OSSupportsIPv6)
{
return null;
}
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;
if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up)
#endif
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
//IPv4
if (Addfam == ADDRESSFAM.IPv4)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
//IPv6
else if (Addfam == ADDRESSFAM.IPv6)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
{
output = ip.Address.ToString();
}
}
}
}
}
return output;
}
}
public enum ADDRESSFAM
{
IPv4, IPv6
}
这篇关于如何在Unity 2018+中获取设备的IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!