用linux c写dns报文查询代码
时间: 2023-02-28 21:24:55 浏览: 158
Linux下的DHCP客户端,纯C代码
下面是一个简单的 DNS 查询代码,使用 C 语言在 Linux 上编写:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define DNS_QUERY_PORT 53
#define DNS_SERVER_IP "8.8.8.8"
#define DNS_QUERY_NAME "www.google.com"
struct DNS_HEADER
{
unsigned short id;
unsigned char rd :1;
unsigned char tc :1;
unsigned char aa :1;
unsigned char opcode :4;
unsigned char qr :1;
unsigned char rcode :4;
unsigned char cd :1;
unsigned char ad :1;
unsigned char z :1;
unsigned char ra :1;
unsigned short q_count;
unsigned short ans_count;
unsigned short auth_count;
unsigned short add_count;
};
struct QUESTION
{
unsigned short qtype;
unsigned short qclass;
};
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in serv_addr;
char send_buf[1024];
char recv_buf[1024];
int send_len;
int recv_len;
// 创建套接字
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
perror("socket error");
exit(EXIT_FAILURE);
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(DNS_QUERY_PORT);
serv_addr.sin_addr.s_addr = inet_addr(DNS_SERVER_IP);
struct DNS_HEADER *dns = (struct DNS_HEADER *)send_buf;
struct QUESTION *qinfo = (struct QUESTION *)(send_buf + sizeof(struct DNS_HEADER));
dns->id = (unsigned short)htons(getpid());
dns->qr = 0;
dns->opcode = 0;
dns->aa = 0;
dns->tc = 0;
dns->rd = 1;
dns->ra = 0;
dns->z = 0;
dns->ad = 0;
dns->cd = 0;
dns->rcode = 0;
dns->q_count = htons(1);
dns->ans_count = 0;
dns->auth_count = 0;
dns->add_count = 0;
qinfo->qtype = htons(1);
阅读全文