用c++在Linux下读取ICMP应答
Reading ICMP reply with select in Linux using C++
我正在使用c++和原始套接字向路由器发送ICMP请求,之后我想读取ICMP应答。我的问题是,select()没有一直接收重放和超时。我没有得到任何错误(errno返回成功)。路由器正在发送ICMP应答,因为我可以通过Wireshark看到响应。
https://i.stack.imgur.com/exdAI.png wireshark截图
为了测试我的程序,我使用Ubuntu 12.10在VirtualBox 4.2.6和GN3上运行虚拟网络。
源代码:
char buffer[IP_MAXPACKET]; // for the received ICMP reply
struct iphdr *ipRec; // ICMP header
timeval tv; // timeout
fd_set mySet; // descriptor set
...
tv.tv_sec = 3; // default time-out 3s
tv.tv_usec = 0;
int retval; // select
...
do {
FD_ZERO(&mySet);
FD_SET(mysocket, &mySet);
retval = select(mysocket+1, &mySet, NULL, NULL, &tv);
cout << "Errno after select:" << strerror(errno) << endl;
if(retval == -1) {
cerr << "select error" << endl;
break;
}
else if (retval) {
if((length = recvfrom(mysocket, buffer, MAX, 0, result->ai_addr, &(result->ai_addrlen))) == -1) {
cerr << "Error: while receiving data." << endl;
}
else {
cout << "good" << endl;
ipRec = (struct iphdr*) buffer;
icmpRec = (struct icmphdr*) (buffer + ipRec->ihl * 4);
cout << "the packet." << " PID: " << ntohs(icmpRec->un.echo.id) << " Seq: " << ntohs(icmpRec->un.echo.sequence) << endl;
if ((icmpRec->type == ICMP_ECHOREPLY) && (ntohs(icmpRec->un.echo.id) == pid) && (ntohs(icmpRec->un.echo.sequence) == (seq - 1))) {
minBuff = lengthBuff;
}
}
} else {
// getting here all the time = select times-out and reads no data
cout << "mysocket:" << mysocket << endl;
cout << "retval:" << retval << endl;
maxBuff = lengthBuff;
break;
}
} while (!((icmpRec->type == ICMP_ECHOREPLY) && (ntohs(icmpRec->un.echo.id) == pid) && (ntohs(icmpRec->un.echo.sequence) == (seq - 1))));
if (packet)
delete(packet);
...
谢谢你的帮助。
修复问题。在不同的线程中找到了解决方案:ICMP数据包没有被发送C.将IPPROTO_RAW更改为IPPROTO_ICMP修复了它。现在选择读取ICMP应答报文
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 使用RAW套接字读取ICMP响应
- 读取 ICMP 回显请求数据
- 用c++在Linux下读取ICMP应答