|
3 | 3 |
|
4 | 4 | from __future__ import absolute_import |
5 | 5 | import socket |
6 | | -import fcntl |
7 | 6 | import struct |
8 | 7 | import sys |
9 | 8 |
|
10 | | -if sys.version_info >= (3, 0): |
11 | | - |
| 9 | +if sys.platform == "win32": |
| 10 | + import psutil |
12 | 11 | 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") |
14 | 15 |
|
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 |
25 | 21 |
|
| 22 | + raise ValueError(f"No MAC address found for interface '{ifname}'") |
26 | 23 | 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] |
27 | 40 |
|
28 | | - def get_hw(ifname): |
29 | | - """Returns a unicode string containing the MAC address of the interface. |
| 41 | + else: |
30 | 42 |
|
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. |
38 | 45 |
|
| 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] |
39 | 53 |
|
40 | 54 | def to_str(data, separator=":"): |
41 | 55 | """Stringify hexadecimal input; |
|
0 commit comments