从DNS获取IP

时间:2015-10-30 17:39:51

标签: c# tcp dns udp

如何使用TCP创建数据流以查找某个域的IP? 搜索论坛并尝试这样的事情:

client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("8.8.8.8"), 53);
client.Connect(ep);
String query = "host -T google.com";
byte[] myByte = System.Text.ASCIIEncoding.Default.GetBytes(query);
client.Send(myByte, myByte.Length);
var receivedData = client.Receive(ref ep);

我不了解如何为DNS服务器创建正确的消息。如果存在类似于HTTP方式的东西,那就太棒了。

更新:您就是这样做的!

    client = new UdpClient();
    IPEndPoint ep = new IPEndPoint(IPAddress.Parse("8.8.8.8"), 53);
    client.Connect(ep);

    //dynamic dns
    String host1 = "vg.no";
    byte[] hostnameLength = new byte[1];
    byte[] hostdomainLength = new byte[1];


    byte[] tranactionID1 = { 0x46, 0x62 };
    byte[] queryType1 = { 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    byte[] hostname = System.Text.ASCIIEncoding.Default.GetBytes(host1.Split('.')[0]);
    hostnameLength[0] = (byte)hostname.Length;
    byte[] hostdomain = System.Text.ASCIIEncoding.Default.GetBytes(host1.Split('.')[1]);
    hostdomainLength[0] = (byte)hostdomain.Length;
    byte[] queryEnd = {0x00, 0x00, 0x01, 0x00, 0x01};
    byte[] dnsQueryString = tranactionID1.Concat(queryType1).Concat(hostnameLength).Concat(hostname).Concat(hostdomainLength).Concat(hostdomain).Concat(queryEnd).ToArray();
    client.Send(dnsQueryString, dnsQueryString.Length);

1 个答案:

答案 0 :(得分:0)

如果问题只是“在C#中从DNS获取域名的IP”,那么简单的答案就是

var res = Dns.GetHostEntry("google.com").AddressList;

此语句返回一个字符串数组,其IP地址为已解析的域名。

如果问题更复杂“使用TCP / IP协议从C#中获取DNS的域名”,请查看here