forked from hellogavin/UnityUtils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DNS.cs
105 lines (93 loc) · 2.29 KB
/
DNS.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
using System;
using UnityEngine;
using System.Net;
namespace X
{
public class DnsEx
{
public static IPAddress GetIPAddress(string host)
{
var hostEntry = Dns.GetHostEntry(host);
foreach (var ip in hostEntry.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
return ip;
}
return null;
}
public static IPAddress GetIPAddressByHttpDns(string host)
{
var webclient = new System.Net.WebClient();
var ip = webclient.DownloadString("http://119.29.29.29/d?dn=" + host);
try
{
return IPAddress.Parse(ip);
}
catch(Exception e)
{
Debug.LogWarning(string.Format("GetIPAddressByHttpDns failed.host:[{0}] ip:[{1}]", host, ip));
throw e;
}
}
public class IPAddressAsyn
{
IPAddress IPAddress;
Exception Exception;
WebRequest WebRequest;
WebResponse WebResponse;
System.IO.Stream Stream;
byte[] Buffer = new byte[128];
int BufferOffset = 0;
public IPAddressAsyn(string url, int millisecondsTimeout)
{
WebRequest = WebRequest.Create(url);
WebRequest.Timeout = millisecondsTimeout;
WebRequest.BeginGetResponse(GetResponseCallback, null);
}
void GetResponseCallback(IAsyncResult asyncResult)
{
try
{
WebResponse = WebRequest.EndGetResponse(asyncResult);
Stream = WebResponse.GetResponseStream();
BufferOffset = 0;
Stream.BeginRead(Buffer, BufferOffset, Buffer.Length, ReadCallback, null);
}
catch(System.Exception e)
{
Exception = e;
}
}
void ReadCallback(IAsyncResult asyncResult)
{
try
{
var size = Stream.EndRead(asyncResult);
if (size <= 0)
{
var ip = System.Text.Encoding.ASCII.GetString(Buffer);
IPAddress = IPAddress.Parse(ip);
return;
}
BufferOffset += size;
Stream.BeginRead(Buffer, BufferOffset, Buffer.Length - BufferOffset, ReadCallback, null);
}
catch(System.Exception e)
{
Exception = e;
}
}
public IPAddress GetIPAddress()
{
if (Exception != null)
throw Exception;
return IPAddress;
}
}
public static IPAddressAsyn GetIPAddressAsynByHttpDns(string host, int millisecondsTimeout)
{
var ret = new IPAddressAsyn("http://119.29.29.29/d?dn=" + host, millisecondsTimeout);
return ret;
}
}
}