Is it possible to use ICMP sockets under the IP protocol? Maybe something like:
socket(PF_INET, <type>, IPPROTO_ICMP)?
What should I put in the < type > 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?
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...
Linux have a special ICMP socket type you can use with:
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:
Here is an example program to demonstrate the very basic usage of sending an ICMP echo request:
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.