Skip to content

Commit e4bdc73

Browse files
committed
feat: Add Windows compatibility
1 parent 019b4bd commit e4bdc73

File tree

1 file changed

+37
-23
lines changed

1 file changed

+37
-23
lines changed

rawsocketpy/util.py

Lines changed: 37 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,53 @@
33

44
from __future__ import absolute_import
55
import socket
6-
import fcntl
76
import struct
87
import sys
98

10-
if sys.version_info >= (3, 0):
11-
9+
if sys.platform == "win32":
10+
import psutil
1211
def get_hw(ifname):
13-
"""Returns a bytearray containing the MAC address of the interface.
12+
addrs = psutil.net_if_addrs()
13+
if ifname not in addrs:
14+
raise ValueError(f"Interface '{ifname}' not found")
1415

15-
:param ifname: Interface name such as ``wlp2s0``
16-
:type ifname: str
17-
:rtype: str
18-
:rtype: bytearray
19-
"""
20-
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
21-
info = fcntl.ioctl(
22-
s.fileno(), 0x8927, struct.pack("256s", bytearray(ifname[:15], "utf-8"))
23-
)
24-
return info[18:24]
16+
for snic in addrs[ifname]:
17+
if snic.family == psutil.AF_LINK:
18+
mac_str = snic.address.replace("-", ":")
19+
mac_bytes = bytearray(int(b, 16) for b in mac_str.split(":"))
20+
return mac_bytes
2521

22+
raise ValueError(f"No MAC address found for interface '{ifname}'")
2623
else:
24+
import fcntl
25+
if sys.version_info >= (3, 0):
26+
27+
def get_hw(ifname):
28+
"""Returns a bytearray containing the MAC address of the interface.
29+
30+
:param ifname: Interface name such as ``wlp2s0``
31+
:type ifname: str
32+
:rtype: str
33+
:rtype: bytearray
34+
"""
35+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
36+
info = fcntl.ioctl(
37+
s.fileno(), 0x8927, struct.pack("256s", bytearray(ifname[:15], "utf-8"))
38+
)
39+
return info[18:24]
2740

28-
def get_hw(ifname):
29-
"""Returns a unicode string containing the MAC address of the interface.
41+
else:
3042

31-
:param ifname: Interface name such as ``wlp2s0``
32-
:type ifname: str
33-
:rtype: str
34-
"""
35-
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
36-
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack("256s", ifname[:15]))
37-
return info[18:24]
43+
def get_hw(ifname):
44+
"""Returns a unicode string containing the MAC address of the interface.
3845
46+
:param ifname: Interface name such as ``wlp2s0``
47+
:type ifname: str
48+
:rtype: str
49+
"""
50+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
51+
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack("256s", ifname[:15]))
52+
return info[18:24]
3953

4054
def to_str(data, separator=":"):
4155
"""Stringify hexadecimal input;

0 commit comments

Comments
 (0)