Python Raw Socket - IP_HDRINCL Option
According to the man page for raw sockets
The IPv4 layer generates an IP header when a packet is sent, unless the IP_HDRINCL Socket Option is enabled on the socket. When enabled, the packet must contain an IP header. To obtain the IP header, it is always included in the packet.
I am using python to check the IP_HDRINCL socket option, so I created an IP header, but after enabling the option, unfortunately the sendto () method doesn't seem to work, I got the following error
Traceback (last call last): File "./test.py", line 35, in s.sendto (pkt, (dip, 0)) socket.error: [Errno 1] Operation not allowed
just keep in mind that I am running the program with uid 0 (root)
Note:
I don't want to use raw socket along with PACKET FAMILY, I still want to use the TCP / IP stack implemented in the kernel
Here's a sample I created:
#!/usr/bin/env python
import socket
import struct
def IP():
version = 4
ihl = 5
DF = 0
Tlen = 0
ID = 0
Flag = 0
Fragment = 0
TTL = 64
Proto = socket.IPPROTO_TCP
ip_checksum = 0
SIP = socket.inet_aton("172.16.122.2")
DIP = socket.inet_aton("172.16.122.1")
ver_ihl = (version << 4) + ihl
f_f = (Flag << 13) + Fragment
ip_hdr = struct.pack("!BBHHHBBH4s4s", ver_ihl,DF,Tlen,ID,f_f,TTL,Proto,ip_checksum,SIP,DIP)
return ip_hdr
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
# the error occurs only when the IP_HDRINCL is enabled
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
dip = "172.16.122.1"
pkt = IP() + "Hello"
s.sendto(pkt, (dip , 0 ))
source to share