-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHostAddress.cs
113 lines (99 loc) · 3.32 KB
/
HostAddress.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using System.Net;
using System.Net.Sockets;
namespace BV5Tl0N.HostAddress
{
public static class HostAddress
{
public static bool IsHostValid(string host)
{
if (!string.IsNullOrEmpty(host))
return IsValidIP(host) || IsValidFQDN(host);
return false;
}
public static bool IsPrivate(string host)
{
if (!string.IsNullOrEmpty(host))
{
if (IsValidIP(host))
{
if (IPAddress.IsLoopback(IPAddress.Parse(host)))
return true;
if (IsInPrivateRange(host))
return true;
}
if (IsValidFQDN(host))
{
IPAddress[] ipAddresses = Dns.GetHostAddresses(host);
foreach (IPAddress ipAddress in ipAddresses)
{
if (IPAddress.IsLoopback(ipAddress))
return true;
if (IsInPrivateRange(ipAddress.ToString()))
return true;
}
}
}
return false;
}
public static bool IsValidFQDN(string host)
{
if (!string.IsNullOrEmpty(host))
{
try
{
Dns.GetHostEntry(host);
return true;
}
catch (Exception)
{
return false;
}
}
return false;
}
public static bool IsValidIP(string host)
{
if (!string.IsNullOrEmpty(host))
return IPAddress.TryParse(host, out _);
return false;
}
public static bool IsValidIPv4(string host)
{
if (!string.IsNullOrEmpty(host))
return IPAddress.TryParse(host, out _) && IPAddress.Parse(host).AddressFamily == AddressFamily.InterNetwork;
return false;
}
public static bool IsValidIPv6(string host)
{
if (!string.IsNullOrEmpty(host))
return IPAddress.TryParse(host, out _) && IPAddress.Parse(host).AddressFamily == AddressFamily.InterNetworkV6;
return false;
}
private static bool IsInPrivateRange(string host)
{
if (!string.IsNullOrEmpty(host))
{
IPAddress ip = IPAddress.Parse(host);
byte[] ipBytes = ip.GetAddressBytes();
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
if (ipBytes[0] == 10 ||
ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31 ||
ipBytes[0] == 192 && ipBytes[1] == 168)
{
return true;
}
}
if (ip.AddressFamily == AddressFamily.InterNetworkV6)
{
if (ipBytes[0] == 0xFD && (ipBytes[1] & 0xC0) == 0x80 ||
ipBytes[0] == 0xFE && (ipBytes[1] & 0xC0) == 0xC0)
{
return true;
}
}
}
return false;
}
}
}