Skip to content

Instantly share code, notes, and snippets.

@travelhawk
Created March 19, 2019 15:59
Show Gist options
  • Save travelhawk/b4fe9171b3915f28a4e7f9edff57a9b9 to your computer and use it in GitHub Desktop.
Save travelhawk/b4fe9171b3915f28a4e7f9edff57a9b9 to your computer and use it in GitHub Desktop.
Use this class to obtain the ip on different platforms including HoloLens using Unity3D as a development platform.
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
#if WINDOWS_UWP
using Windows.Networking.Connectivity;
using Windows.Networking;
#endif
/// <summary>
/// Get the ip of the actual device. Also works on UWP (e.g. HoloLens).
///
/// Michael Falk
/// </summary>
public static class IpManager
{
public enum AddressType
{
IPv4, IPv6
}
public static string GetIp(AddressType type)
{
string ip = "";
#if WINDOWS_UWP
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
if (localHostName.IPInformation != null)
{
if (localHostName.Type == HostNameType.Ipv4)
{
ip = localHostName.ToString();
break;
}
}
}
#else
List<string> IPs = GetAllIPs(type, false);
if (IPs.Count > 0)
{
ip = IPs[IPs.Count - 1];
}
#endif
return ip;
}
#if !WINDOWS_UWP
public static List<string> GetAllIPs(AddressType type, bool includeDetails)
{
//Return null if ADDRESSFAM is Ipv6 but Os does not support it
if (type == AddressType.IPv6 && !Socket.OSSupportsIPv6)
{
return null;
}
List<string> output = new List<string>();
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS
NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;
bool isCandidate = (item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2);
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
// as of MacOS (10.13) and iOS (12.1), OperationalStatus seems to be always "Unknown".
isCandidate = isCandidate && item.OperationalStatus == OperationalStatus.Up;
#endif
if (isCandidate)
#endif
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
//IPv4
if (type == AddressType.IPv4)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
string s = ip.Address.ToString();
if (includeDetails)
{
s += " " + item.Description.PadLeft(6) + item.NetworkInterfaceType.ToString().PadLeft(10);
}
output.Add(s);
}
}
//IPv6
else if (type == AddressType.IPv6)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
{
output.Add(ip.Address.ToString());
}
}
}
}
}
return output;
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment