ICMP sockets (linux)

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

Is it possible to use ICMP sockets under the IP protocol? Maybe something like:

socket(PF_INET, , IPPROTO_ICMP)?

What should I put in the field? I saw some examples using SOCK_RAW, but won't that prevent the OS from doing his job handling the IP protocol?

And another thing. How can the OS know to which process he should send the ICMP datagrams, since there are no ports involved with the protocol?

回答1:

Yes it is possible, since the ping command does ICMP.

To find out the syscalls involved, you can strace that command (under root).

You could also glance into that command's source code, e.g. Debian's ping

And there is the liboping library to help you...



回答2:

Linux have a special ICMP socket type you can use with:

  socket(PF_INET, SOCK_DGRAM IPPROTO_ICMP); 

This allows you to only send ICMP echo requests The kernel will handle it specially (match request/responses, fill in the checksum).

This only works if a special sysctl is set. By default not even root can use this kind of socket. You specify the user groups that can access it. To allow root (group 0) to use ICMP sockets, do:

 sysctl -w net.ipv4.ping_group_range="0 0" 

Here is an example program to demonstrate the very basic usage of sending an ICMP echo request:

#include  #include  #include  #include  #include  #include  #include  #include  #include  #include   //note, to allow root to use icmp sockets, run: //sysctl -w net.ipv4.ping_group_range="0 0"  void ping_it(struct in_addr *dst) {     struct icmphdr icmp_hdr;     struct sockaddr_in addr;     int sequence = 0;     int sock = socket(AF_INET,SOCK_DGRAM,IPPROTO_ICMP);     if (sock 

Note that the kernel will reject and fail the sendto() call if the data sent does not have room for a proper ICMP header, and the ICMP type must be 8 (ICMP_ECHO) and the ICMP code must be 0.



文章来源: ICMP sockets (linux)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!