为什么recvfrom()收不到数据?
int main(int argc, char* argv[]){
sockaddr_in dest,local;
int timeout=5000;
char d_addr[]="127.0.0.1";
WSADATA wsaData;
int net=WSAStartup(MAKEWORD(2,2),&wsaData);
if (net!=0)
return 0;
SOCKET s_icmp=socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
if(s_icmp==INVALID_SOCKET)
printf("origi socket error\n");
setsockopt(s_icmp,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout,sizeof(timeout));
unsigned long cmd=0;
ioctlsocket(s_icmp,FIONBIO,&cmd);
local.sin_family=AF_INET;
local.sin_port=htons(0);
local.sin_addr.s_addr=INADDR_ANY;
//FILL UP THE RECEIVE ADDRESS STRUCT
if(bind(s_icmp,(sockaddr*)&local,sizeof(local))!=0)
{
printf("%d",::GetLastError());
return 0;
}
char buf[sizeof(ICMP_HDR)+32];//32为数据部分,icmp头+数据部分
memset(buf,'a',sizeof(ICMP_HDR)+32);
ICMP_HDR *picmp=(ICMP_HDR*)buf;
//将一个icmp头结构的指针,指向buf
dest.sin_family=AF_INET;
dest.sin_port=htons(0);
dest.sin_addr.s_addr=inet_addr(d_addr);
//fill up the destation address struct
picmp->icmp_type=8;
picmp->icmp_code =0;
picmp->icmp_id=(USHORT)::GetCurrentProcessId();
picmp->checksum=0;
picmp->icmp_seq=0;
//INITIALIZE the protocol header
int cou=0;
char recvbuf[512];
sockaddr_in from;
int fromlen=sizeof(from);
while(cou<4)
{
picmp->checksum=0;
picmp->icmp_timestamp=(USHORT)::GetTickCount();
picmp->icmp_seq=cou;
picmp->checksum=checksum((USHORT*) buf,sizeof(ICMP_HDR)+32);
//FILL UP THE PACKET THAT STANDBY
int size=sendto(s_icmp,buf,sizeof(ICMP_HDR)+32,0,(sockaddr*)&dest,sizeof(dest));
//send icmp packet to dest
if(size==SOCKET_ERROR)
{
printf("sendto() failed\n");
return 0;
};
int rsize=recvfrom(s_icmp,recvbuf,512,0,(sockaddr*)&from,&fromlen);
//receive packet from the dest
if(rsize==SOCKET_ERROR)
{
printf("recvfrom() failed %d \n",::WSAGetLastError());
getchar();
}
if (size<sizeof(ICMP_HDR)+20)
printf("the packet too small\n");
ICMP_HDR *p=(ICMP_HDR*)recvbuf+20;
//pointer *p point to received packet and IP header
if(p->icmp_type!=0)
{
printf("noneecho packet\n");
return 0;
}
if(p->icmp_id!=GetCurrentProcessId())
{
printf("other process's packet\n");
return 0;
}
printf("%d bytes form %s ,",size,inet_ntoa(from.sin_addr));
printf("sequence: %d ,%d ms\n",4-cou,p->icmp_timestamp);
::Sleep(1000);
cou++;
}
getchar();
closesocket(s_icmp);
//closesocket(s);
WSACleanup();
return 0;
}