0

How Do I Use Raw Socket in Python?

I see the following code is used to send raw packet.

s = socket(AF_PACKET, SOCK_RAW)
s.bind(("eth1", 0))
...
s.send(dst_addr+src_addr+ethertype+payload+checksum)

But when I try it on Mac, I see this. I am not sure what is the appropriate way to send a raw packet on MacOS. Could anybody let me know?

NameError: name 'AF_PACKET' is not defined

Here is what is shown on help page of macOS. Is any of them appropriate?

     |  AF_APPLETALK = <AddressFamily.AF_APPLETALK: 16>
     |
     |  AF_INET = <AddressFamily.AF_INET: 2>
     |
     |  AF_INET6 = <AddressFamily.AF_INET6: 30>
     |
     |  AF_IPX = <AddressFamily.AF_IPX: 23>
     |
     |  AF_LINK = <AddressFamily.AF_LINK: 18>
     |
     |  AF_ROUTE = <AddressFamily.AF_ROUTE: 17>
     |
     |  AF_SNA = <AddressFamily.AF_SNA: 11>
     |
     |  AF_SYSTEM = <AddressFamily.AF_SYSTEM: 32>
     |
     |  AF_UNIX = <AddressFamily.AF_UNIX: 1>
     |
     |  AF_UNSPEC = <AddressFamily.AF_UNSPEC: 0>
user1424739
  • 11,937
  • 17
  • 63
  • 152

1 Answers1

0

Example

import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    packet = create_packet()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.sendto(packet, (ip, port))
import socket
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect(("localhost", 8080))
socket.send("content")
socket.close()

Here is an example python file that sends wakeonlan magic packets.

Here are some examples from socket documentation

Huakun Shen
  • 312
  • 2
  • 9
  • 1
    I don't think this is equivalent. In my example, it is not a TCP/IP packet. Is just an IP packet? (ICMP packet should be sent by that piece of code on Linux.) – user1424739 Feb 25 '21 at 03:59