|   下面可以利用Raw Socket发送生成的ICMP报文: //功能:发送生成的ICMP包//返回值:<0 发送失败
 int send_ping(SOCKET sd, const sockaddr_in &dest, ICMPHeader *send_buf, int packet_size)
 {
 // 发送send_buf缓冲区中的报文
 cout << "Sending " << packet_size << " bytes to " << inet_ntoa(dest.sin_addr)
 << "..." << flush;
 int bwrote = sendto(sd, (char*)send_buf, packet_size, 0, (sockaddr*) &dest,sizeof(dest));
 if (bwrote == SOCKET_ERROR)
 {
 cerr << "send failed: " << WSAGetLastError() << endl;
 return - 1;
 }
 else if (bwrote < packet_size)
 {
 cout << "sent " << bwrote << " bytes..." << flush;
 }
 return 0;
 }
   发送Ping报文后,我们需要接收Ping回复ICMP报文: //功能:接收Ping回复//返回值: <0 接收失败
 int recv_ping(SOCKET sd, sockaddr_in &source, IPHeader *recv_buf, int packet_size)
 {
 // 等待Ping回复
 int fromlen = sizeof(source);
 int bread = recvfrom(sd, (char*)recv_buf, packet_size + sizeof(IPHeader), 0,(sockaddr*) &source, &fromlen);
 if (bread == SOCKET_ERROR)
 {
 cerr << "read failed: ";
 if (WSAGetLastError() == WSAEMSGSIZE)
 {
 cerr << "buffer too small" << endl;
 }
 else
 {
 cerr << "error #" << WSAGetLastError() << endl;
 }
 return - 1;
 }
 return 0;
 }
   并使用如下函数对接收到的报文进行解析: 
// 功能:解析接收到的ICMP报文// 返回值: -2忽略, -1失败, 0 成功
 int decode_reply(IPHeader *reply, int bytes, sockaddr_in *from)
 {
 // 偏移到ICMP报头
 unsigned short header_len = reply->h_len *4;
 ICMPHeader *icmphdr = (ICMPHeader*)((char*)reply + header_len);
 
 // 报文太短
 if (bytes < header_len + ICMP_MIN)
 {
 cerr << "too few bytes from " << inet_ntoa(from->sin_addr) << endl;
 return - 1;
 }
 // 解析回复报文类型
 else if (icmphdr->type != ICMP_ECHO_REPLY)
 {
 
		      
		      
		      
		      
		      
		      
                        共9页: 上一页 [1] [2] [3] [4] 5 [6] [7] [8] [9] 下一页 |