How do I send an ICMP packet over sockets?

I am trying to send a message via ICMP packets, but I have no idea how.

This is the code I have, but obviously doesn't work:

s.setsockopt(IPPROTO_IP, IP_HDRINCL, 1)
s.sendto("Hello!" + "\r\n", (server, 7))
msg = s.recvfrom(buff_size)


I need to get a response from the server if the string "Hello!" is sent, but I don't understand it. I guess "Hello!" the string will be encapsulated in the data field:

enter image description here


source to share

2 answers

To create an ICMP packet, you must create the entire packet yourself using a raw socket. The struct

is useful for this .

Second, to even use the original sockets in the first place, you need to have permission to do so - you must be running as root (I know this is a sufficient condition, but I'm not 100% sure that it is a necessary condition). The executable ping(1)

can do this because it is executing a setuid executable that runs as root when it starts. Since scripts cannot be setuid on Linux, you will need to make a shell setuid program in C that will simply execute your Python script.



I don't think I'm SOCK_RAW

sending you an ICMP datagram just because you set the protocol field to a value IPPROTO_ICMP

! You must create the package yourself.

Take a look at the ping source.

There are (at least) two popular packages that are provided ping

on GNU / Linux operating systems. One of them is netkit

and the other iputils

. ( netkit-combo

is a tarball that has all the utilities netkit

in one: telnet, FTP, ...). The BSD guys might have their own.



All Articles