-
Notifications
You must be signed in to change notification settings - Fork 7
/
HostName.cs
102 lines (86 loc) · 2.19 KB
/
HostName.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace Hosts;
public class HostName
{
private static IdnMapping IdnMapping = new IdnMapping();
public string Ascii { get; protected set; }
public string Unicode { get; protected set; }
public bool Idn { get; protected set; }
public HostName(string host)
{
if (host == null) { throw new ArgumentNullException(); }
try
{
host = host.ToLower();
if (Uri.CheckHostName(host) != UriHostNameType.Dns) { throw new Exception(); }
if (host.StartsWith("xn--") || host.Contains(".xn--"))
{
Unicode = IdnMapping.GetUnicode(host);
Ascii = IdnMapping.GetAscii(Unicode);
}
else
{
Ascii = IdnMapping.GetAscii(host);
Unicode = IdnMapping.GetUnicode(Ascii);
}
Idn = Ascii != Unicode;
}
catch (Exception e)
{
throw new FormatException($"Invalid host '{host}'.", e);
}
}
public static HostName TryCreate(string host)
{
try { return new HostName(host); }
catch { return null; }
}
public static implicit operator HostName(string host)
{
return new HostName(host);
}
public static implicit operator string(HostName host)
{
return host.ToString();
}
public override string ToString()
{
return Idn ? Unicode : Ascii;
}
public string ToString(bool idn)
{
return idn ? Unicode : Ascii;
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public bool Equals(HostName host)
{
if ((object)host == null) { return false; }
return host.Unicode == this.Unicode;
}
public bool Equals(string host)
{
return Equals(HostName.TryCreate(host));
}
public override bool Equals(object obj)
{
if (obj == null) { return false; }
if (obj is string) { return Equals((string)obj); }
if (obj is HostName) { return Equals((HostName)obj); }
return false;
}
public static bool operator ==(HostName hn1, HostName hn2)
{
return Object.ReferenceEquals(hn1, hn2) || hn1.Equals(hn2);
}
public static bool operator !=(HostName hn1, HostName hn2)
{
return !(Object.ReferenceEquals(hn1, hn2) || hn1.Equals(hn2));
}
}