2010-03-04 62 views
0

我只想寫使用C套接字的DNS客戶端程序, 需要三個參數:查詢名稱(例如主機名或域名)和查詢類型(A或NS,或MX)和DNS服務器名稱。在收到的DNS記錄的答案部分打印出答案。使用C套接字編寫的DNS客戶端

我知道有一個命令getaddrinfo .. ,但我只是想連接到查找表,然後 獲得DNS服務器名稱...

所以當我給./a.out WWW輸入.google.com一個144.20.190.70

它會顯示一些與此類似:

服務器:144.20.190.70 地址:144.20.190.70#53

非-authoritative答案:

名稱:www.google.com

規範名稱:www.l.google.com

名稱:www.l.google.com 地址:74.125.19.104

名稱:www.l.google.com 地址:74.125.19.105

名稱:www.l.google.com 地址:74.125.19.106

名稱:www.l.google.com 地址:74.125.19.147

名稱:www.l.google.com 地址:74.125.19.99

名稱:www.l.google.com 地址:74.125.19.103

+0

您需要更清楚地提出問題。 你不想做getaddrinfo;這個問題很明顯,但'dns srname'呢?你應該考慮改寫這個問題。 – rmk 2010-03-04 21:33:06

+0

請幫我一下 – SuperMan 2010-03-04 22:34:07

回答

2

是的,你需要看到的是羅布 - 菲爾波特爲.NET

Click Here

做出Bev.net.dns類建立發送到DNS服務器的請求並不容易,但是一旦您可以從服務器獲得答案,那麼您需要將其發送回瀏覽器,這就是我陷入困境的一點。

我在端口53/UDP上偵聽並獲取請求並將其發送到DNS服務器並獲得有效的響應,但之後我將它發送回瀏覽器使用遠程客戶端端口作爲UDP,但瀏覽器不會除外答覆。

Robs代碼真的很容易使用,如下圖所示「Resolver.Lookup」,我只需要添加一點,以便從DNS服務器發送的原始字節數組保存在Resolver.Message中,準備發送回瀏覽器。

public void Listen() 
    { 
     receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
     receiveEndPoint = new IPEndPoint(IPAddress.Any, receivePort); receiveSocket.Bind(receiveEndPoint); 
     receivePort = (receiveSocket.LocalEndPoint as IPEndPoint).Port; 
     receiveBuffer = new byte[BufferSize]; 
     receiveAsyncResult = receiveSocket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref receiveEndPoint, new AsyncCallback(NetworkMessageReceivedCallback), receiveSocket); 
    } 


    public void NetworkMessageReceivedCallback(IAsyncResult asyncResult) 
    { 
     EndPoint remoteEndPoint = null;    
     byte[] bytes = null;       
     remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); //Will contain the clients port     
     int bytesRead = receiveSocket.EndReceiveFrom(asyncResult, ref remoteEndPoint);            
     bytes = new Byte[bytesRead];     
     Buffer.BlockCopy(receiveBuffer, 0, bytes, 0, bytesRead); 
     //string ip = "208.67.222.222"; 
     string ip = "192.168.1.254"; 
     IPAddress dnsServer = IPAddress.Parse(ip); 
     Response R = Resolver.Lookup(bytes, dnsServer); 
     receiveSocket.SendTo(R.Message , remoteEndPoint);//127.0.0.1 
     receiveSocket.Close(); 
    Listen(); 
}