dnsリクエストパッケージ

2920 ワード

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

void getQueryPacket(char *DNSsendBuff);

#define ADDRESS "172.16.20.132"
#define PORT 53

typedef struct
{
	unsigned short id;
	unsigned short flags;
	unsigned short questNum;
	unsigned short answerNum;
	unsigned short authorNum;
	unsigned short additionNum;
}DNSHDR,*pDNSHDR;

typedef struct
{
	unsigned short type;
	unsigned short class;
}QUERYHDR,*pQUERYHDR;

void getQueryPacket(char *DNSsendBuff)
{
	bzero(DNSsendBuff,sizeof(DNSsendBuff));
	pDNSHDR pDnsHdr = (pDNSHDR)malloc(sizeof(DNSHDR));
	pQUERYHDR pQueryHdr = (pQUERYHDR)malloc(sizeof(QUERYHDR));

	pDnsHdr->id = htons(0xde76);
	pDnsHdr->flags = htons(0x0100);
	pDnsHdr->questNum = htons(0x0001);
	pDnsHdr->answerNum = htons(0x0000);
	pDnsHdr->authorNum = htons(0x0000);
	pDnsHdr->additionNum = htons(0x0000);
	memcpy(DNSsendBuff,pDnsHdr,sizeof(DNSHDR));

	char *name = (char *)malloc(15 * sizeof(char));
	char num;
	char *url;
	int cur = 0;
	//3www5baidu3com0
	num = 0x03;
	url = "www";
	memcpy(name + cur,&num,sizeof(num));
	cur += sizeof(num);
	memcpy(name + cur,url,strlen(url));
	cur += strlen(url);

	num = 0x05;
	url = "baidu";
	memcpy(name + cur,&num,sizeof(num));
	cur += sizeof(num);
	memcpy(name + cur,url,strlen(url));
	cur += strlen(url);

	num = 0x03;
	url = "com";
	memcpy(name + cur,&num,sizeof(num));
	cur += sizeof(num);
	memcpy(name + cur,url,strlen(url));
	cur += strlen(url);

	num = 0x00;
	memcpy(name + cur,&num,sizeof(num));

	memcpy(DNSsendBuff + sizeof(DNSHDR),name,15);

	pQueryHdr->type = htons(0x0001);
	pQueryHdr->class = htons(0x0001);
	memcpy(DNSsendBuff + sizeof(DNSHDR) + 15,pQueryHdr,sizeof(QUERYHDR));
}

int main(int argc,char **argv)
{
	char sendBuff[128];
	char recvBuff[1024];
	int sockfd;
	socklen_t serverlen;
	int fd,res;
	struct sockaddr_in serveraddr;

	bzero(&serveraddr,sizeof(struct sockaddr_in));
	bzero(sendBuff,sizeof(sendBuff));
	bzero(recvBuff,sizeof(recvBuff));

	sockfd = socket(AF_INET,SOCK_DGRAM,0);
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(PORT);
	inet_aton(ADDRESS,&serveraddr.sin_addr);

	serverlen = sizeof(serveraddr);
	getQueryPacket(sendBuff);
	fd = open("test",O_CREAT | O_RDWR,S_IRUSR | S_IWUSR);
	write(fd,sendBuff,sizeof(sendBuff));
	close(fd);

	res = sendto(sockfd,sendBuff,31,0,(struct sockaddr *)&serveraddr,serverlen);
	printf("send %d
",res); res = recvfrom(sockfd,recvBuff,sizeof(recvBuff),0,(struct sockaddr *)&serveraddr,&serverlen); printf("recv %d
",res); return 0; }