1

I want to create a raw socket in Windows to connect to a specific interface on my laptop. I have it working on Linux but it does not work in Windows.

This is my code that is fine in Linux but not in Windows:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
#s.bind(("192.168.1.100", 0))
s.bind((socket.gethostname(), 0))
#s.bind((socket.gethostbyname(socket.gethostname()), 0))

The commented out lines are suggestions I found here: Python Raw Socket to Ethernet Interface (Windows) but they did not work for me. I always get this error:

Traceback (most recent call last):
  File "D:/raw_socket.py", line 5, in <module>
    s.bind((socket.gethostname(), 0))
OSError: [WinError 10022] An invalid argument was supplied

I was unable to find a solution while researching this problem. Any help is highly appreciated.

JRsz
  • 2,891
  • 4
  • 28
  • 44

1 Answers1

0

I added an answer on the other post: https://stackoverflow.com/a/53681616/5459467 You can check it for code examples

Short-answer: you can’t natively in Python, due to windows limitations

But you can work around it using Npcap / Winpcap. However, this requires to have a compatibility wrapper between it and Python (they only provide a dll API to use)

Various of those wrappers exist, the most cross-platform one being scapy, as it creates sockets that will use Npcap/Winpcap on Windows, the socket module on Linux, pcapy (or similar) on OSX...

Cukic0d
  • 5,111
  • 2
  • 19
  • 48