原始UDP套接字卡在recvfrom上

时间:2013-03-20 19:44:39

标签: c++ c sockets

我正在通过原始套接字发送dns数据包(类型A)。我的默认DNS服务器得到了很好的结果 问题是我的代码卡在“recvfrom”中,我可以通过wireshark看到传出的请求数据包和传入的答案(没有错误)。我尝试所有类型的操作,如使用不同的套接字传出和传入数据包,尝试“recv”......但似乎没有任何工作。我将不胜感激。

int main() {
char hostname[100];

//Get the DNS servers from the resolv.conf file
get_dns_servers();
struct sockaddr_in sin;
// dest
sin.sin_family = AF_INET;
sin.sin_port = htons (53);
sin.sin_addr.s_addr = inet_addr (dns_servers[0]);

//Get the hostname from the terminal
cout << "\nEnter Hostname to Poison : ";
scanf("%s" , hostname);


//Create a raw socket of type IPPROTO
int s = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);

if(s == -1)
{
    //socket creation failed, may be because of non-root privileges
    perror("Failed to create raw socket");
    exit(1);
}

dns_packet *pak = new dns_packet("192.168.203.128",(uint16_t) 50115,(in_addr_t) sin.sin_addr.s_addr, (in_port_t) sin.sin_port, (int) 3333, hostname);

//Send the packet
if (sendto (s, pak->datagram, pak->iph->tot_len ,   0, (struct sockaddr *) &sin, sizeof (sin)) < 0)
{
    perror("sendto failed");
}
//Data send successfully
else
{
    printf ("Packet Send. Length : %d \n" , pak->iph->tot_len);
}

//Receive the answer
int i = sizeof(sin);
unsigned char buf[65536];

cout << "\nReceiving answer..." << endl;
if(recvfrom (s,(char*)buf , sizeof(buf) , 0 , (struct sockaddr*)&sin , (socklen_t*)&i ) < 0)
{
    perror("recvfrom failed");
}

read_answer(buf);

return 0;

}

1 个答案:

答案 0 :(得分:3)

您的代码中没有绑定调用。您需要先绑定到接口才能收到任何内容。

编辑:另外,我注意到你正在使用原始套接字。使用原始套接字时,使用recvmsg()而不是recvfrom()通常更容易。以下是recvmsg()的链接:http://www.developer.nokia.com/Community/Wiki/Open_C_Sockets:_recv,_recvfrom,_recvmsg_methods