/
GraniteUtil.cs
44 lines (39 loc) · 1.4 KB
/
GraniteUtil.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System.Net;
using System.Net.NetworkInformation;
namespace Granite
{
public class GraniteUtil
{
public const string LocalHost = "127.0.0.1";
public static IPAddress GetBindableAddress(bool ignoreLocalHost)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (var ni in adapters)
{
UnicastIPAddressInformationCollection ips = ni.GetIPProperties().UnicastAddresses;
IPv4InterfaceProperties ipv4 = ni.GetIPProperties().GetIPv4Properties();
foreach (UnicastIPAddressInformation ip in ips)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (ignoreLocalHost && ip.Address.MapToIPv4().ToString() == LocalHost)
{
continue;
}
return ip.Address;
}
}
}
return null;
}
public static IPAddress StringToIpAddress(string hostname)
{
IPAddress serverAddress;
if (!IPAddress.TryParse(hostname, out serverAddress))
{
serverAddress = Dns.GetHostEntry(hostname).AddressList[0];
}
return serverAddress;
}
}
}