DNS域名解析C代码

上篇讲到,要访问如www.baidu.com网站,要先知道www.baidu.com的IP地址。

那么如何根据域名获取IP地址呢?我们来看一下C语言代码

#include 
#include 
#include 
#include 

#pragma comment(lib,"ws2_32.lib")

//定义DNS数据       ID       tag       numq      numa       numa1    numa2
char DNS_DATA[]={0x12,0x34,0x01,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
0x03,0x77,0x77,0x77,0x06,0x66,0x75,0x68,0x6f,0x6d,0x65,0x03,0x6e,0x65,0x74,0x00,//03 www 06 fucome 03 net 00
0x00,0x01,0x00,0x01};//前两字节为1表示A记录; 后两字节为1表示DNS_HDR+域名+DNS_QER


int main(int argc,char* argv[])
{
	WORD socketVersion = MAKEWORD(2,2);
    WSADATA wsaData; 
    if(WSAStartup(socketVersion, &wsaData) != 0)
    {
  		printf("error");      
		return 0;
    }
	//创建UDP通信套接字
    SOCKET sclient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    
    SOCKADDR_IN sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(53);//DNS远程端口固定为53
    sin.sin_addr.S_un.S_addr = inet_addr("114.114.114.114");//DNS服务器IP地址,可以填网关地址如(192.168.0.1)
    
	//发送域名数据
    sendto(sclient, DNS_DATA, sizeof(DNS_DATA), 0, (SOCKADDR *)&sin, sizeof(sin));
 
    char recvData[255];     
    int ret = recv(sclient, recvData, 255, 0);//等待接收数据
    if(ret > 0)//收到大于0的数据
    {
  		for(int i=0;i

返回的结果为:
12 34 81 80 00 01 00 01 00 00 00 00 03 77 77 77 06 66 75 68 6F 6D 65 03 6E 65 74
 00 00 01 00 01 C0 0C 00 01 00 01 00 00 00 F2 00 04 73 1C 5D C9
其中73 lC 5D C9就是为www.fuhome.net的IP地址:115.28.93.201
 

参考资料:龙剑奋斗的博客

你可能感兴趣的:(网络)