本文介绍了如何在 C 中使用原始套接字接收 ICMP 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

这是一个任务,它必须使用原始套接字.我需要编写一个简单的 icmp ping.我以此为基础 http://www.pdbuchan.com/rawsock/icmp4.c .第 127 行是 wlan0,我使用的是 eth0.在第 290 行,我编写了以下代码:

This is an assignment, it has to be with raw sockets. I need to program a simple icmp ping.I used this as a base http://www.pdbuchan.com/rawsock/icmp4.c . At line 127 is wlan0, Im using eth0. In line 290 I coded this:

struct sockaddr_in rec;

unsigned char * pkt = (unsigned char *) malloc (IP_MAXPACKET * sizeof (unsigned char));

if (recvfrom (sd, (void*)pkt, IP4_HDRLEN + ICMP_HDRLEN+datalen , 0, NULL, (socklen_t*)sizeof (struct sockaddr)) < 0)  {
  perror ("recvfrom() failed ");
  exit (EXIT_FAILURE);
}
struct ip *ip = (struct ip *)pkt;
struct icmphdr *icmp = (struct icmphdr *)(pkt + IP4_HDRLEN);

printf("%s %s %d
",(char*)inet_ntoa(*(struct in_addr*)&ip->ip_dst),
        (char*)inet_ntoa(*(struct in_addr*)&ip->ip_src),
        icmp->type);
free (pkt);

问题是 ip_dst 和 ip_src 显示为我机器的 IP,icmp 类型为 0 而不是 8.Wireshark 显示 icmp 回复和请求.可能我的 recvfrom 是错误的,但我听说 linux 自己的 TCP/IP 可能正在处理数据包.如果这是真的,那么解决方法是什么?

The problem is that ip_dst and ip_src are being shown as my machines's IP, and icmp type as 0 and not 8. Wireshark shows both icmp reply and request.Probably my recvfrom is wrong, but I heard something about linux own TCP/IP might be handling the packets. If that's true, what is the workaround for that?

我检查了这个 原始套接字侦听器,但它没有解决我的问题.

edit: I checked this raw socket listener but it did not solve my problem.

推荐答案

我觉得你在使用IPPROTO_RAW时不能得到回复.

I don't think you can get a reply when using IPPROTO_RAW.

你必须使用

socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);

使用 IPPROTO_ICMP,您只能发送一个 ICMP 数据包,而不是整个 IP 数据包.

With IPPROTO_ICMP you must only send an ICMP packet, not the whole IP packet.

但是,当您接收到整个 IP 数据包时,您必须提取 ICMP 回复.请注意,您将获得发送到主机的所有 ICMP 数据包的副本,因此您必须过滤它们.

When receiving however you'll get the whole IP packet and have to extract the ICMP reply. Note that you will get a copy of all ICMP packets sent to the host so you must filter them.

这篇关于如何在 C 中使用原始套接字接收 ICMP 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 16:30