pythonsocketspacket

Python raw manually crafted packets sending problem with socket .sendto()


I am trying to make a packet crafter and analyzer from scratch in python in order to learn, i created the packet, it seems to be fine, also wrote a health check, which the packet passes.

This is how i make the socket:

sock_send = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
sock_send.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

I try to send the packet like so (yes, i also have error checks):

sent_bytes = sock_send.sendto(packet.tobytes(), (Destination_Address, 0))

When i run the program, this happens:

Packet sanity check passed.
=====================================
           IPv4 HEADER
=====================================
IP Version:                    4
Internet Header Length:        20 bytes
DSCP + ECN:                    00000000
Total Length:                  40 bytes
Identification:                27716
Flags:                         010
Fragment Offset:               0
Time To Live (TTL):            64
Protocol:                      6
Header Checksum:               0xfc9a
Source Address:                10.231.5.97
Destination Address:           192.168.1.1
Options:                      (none)

=====================================
              TCP HEADER
=====================================
Source Port:                   12345
Destination Port:              80
Sequence Number:               0
Acknowledgment Number:         0
Data Offset:                   20 bytes
Flags:                         00000000
Window:                        65535
Checksum:                      0x23d6
Urgent Pointer:                0
Options:                      (none)
Data:                         (none)
=====================================

Packet:  0x450000286c4440004006fc9a0ae70561c0a801013039005000000000000000005000ffff23d60000 

Traceback (most recent call last):
  File "/Users/danielmuntean_/Desktop/PacketCrafter/main.py", line 300, in main
    sent_bytes = sock_send.sendto(packet.tobytes(), (Destination_Address, 0))
OSError: [Errno 22] Invalid argument
Failed to send packet: [Errno 22] Invalid argument
Received 0 packets:

can someone help me understand why this happens and how would i fix it?

I looked over the constructing of the packet, it's fine, I looked a bit over the documentation, but still i don't know. I am using macos by the way


Solution

  • I finally found out how do do this, so on the version of macos i am running on(the lastest) raw socket's are EXTREMELY restricted, and so i cannot use raw sockets for my program, and after a bit of research, I found out how nmap bypasses these restrictions: It goes to the Data-Link layer(this may make the program better for multiple platforms without modifying much of the code), thats were the custom packets are injected, so as I am using python, i should use a library like pcapy.

    Thank you very much for your answers!