Linux2.6.32のC++でDNS要求(DNSヘッダー付きのDNSコンテンツ)を受信しようとしています。このコードは、netcatを使用してUDPを介して文字列を書き込むときに機能します。しかし、私が「nslookup google.com」を実行すると、これだけを受け取ります。
root@EliteBook:/home/.../dns# xxd request.bin
0000000: 8a2b 01
また、「tcpdump -x'udp port 53'」を使用すると、さらに多くのバイトが表示されます。
私のC++コード:
#include <string>
#include <iostream>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#define BUFLEN 1024*6
#define NPACK 10
#define PORT 53
using namespace std;
void diep(const string &s)
{
perror(s.c_str());
exit(1);
}
int main()
{
struct sockaddr_in si_me;
struct sockaddr si_other;
int slen=sizeof(si_other);
int s; // UDP Socket
char buf[BUFLEN];
buf[0] = 'X';
buf[1] = 'Y';
buf[2] = 'Z';
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
diep("Failed to create socket!");
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (const sockaddr*) &si_me, sizeof(si_me))==-1)
diep("bind");
for (int i=0; i<NPACK; i++) {
if (recvfrom(s, buf, BUFLEN, 0, &si_other, (socklen_t*) &slen)==-1)
diep("recvfrom()");
struct sockaddr_in *si_other_in = (struct sockaddr_in *)&si_other;
cout << "Pkg arrived: " << buf << " " << inet_ntoa(si_other_in->sin_addr) << ":" << ntohs(si_other_in->sin_port) << endl;
FILE * pFile;
pFile = fopen ("request.bin","wb");
if (pFile!=NULL)
{
fputs (buf, pFile);
fclose (pFile);
}
}
close(s);
return 0;
}
これをコンパイルします
g++ -Wall main.cpp -o dns
それで、私のせいは何ですか、私は何かを忘れましたか、それともバイナリデータを読み取るために別の呼び出しを使用する必要がありますか?
PS:Localhostは/etc/resolv.confの最初のネームサーバーです
編集:
recvfromからの戻り値を見ると、次のように表示されます。
size: **27**
Pkg arrived: �. 127.0.0.1:36686
size: **45**
Pkg arrived: l 127.0.0.1:38952
それは大丈夫なはずです。バッファがすべてのバイトを保持しないのはなぜですか?