|
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): |
| 9 | +if sys.platform == "win32": |
| 10 | + import psutil |
11 | 11 |
|
12 | 12 | def get_hw(ifname): |
13 | | - """Returns a bytearray containing the MAC address of the interface. |
| 13 | + addrs = psutil.net_if_addrs() |
| 14 | + if ifname not in addrs: |
| 15 | + raise ValueError(f"Interface '{ifname}' not found") |
14 | 16 |
|
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] |
| 17 | + for snic in addrs[ifname]: |
| 18 | + if snic.family == psutil.AF_LINK: |
| 19 | + mac_str = snic.address.replace("-", ":") |
| 20 | + mac_bytes = bytearray(int(b, 16) for b in mac_str.split(":")) |
| 21 | + return mac_bytes |
| 22 | + |
| 23 | + raise ValueError(f"No MAC address found for interface '{ifname}'") |
25 | 24 |
|
26 | 25 | else: |
| 26 | + import fcntl |
27 | 27 |
|
28 | | - def get_hw(ifname): |
29 | | - """Returns a unicode string containing the MAC address of the interface. |
| 28 | + if sys.version_info >= (3, 0): |
30 | 29 |
|
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] |
| 30 | + def get_hw(ifname): |
| 31 | + """Returns a bytearray containing the MAC address of the interface. |
| 32 | +
|
| 33 | + :param ifname: Interface name such as ``wlp2s0`` |
| 34 | + :type ifname: str |
| 35 | + :rtype: str |
| 36 | + :rtype: bytearray |
| 37 | + """ |
| 38 | + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 39 | + info = fcntl.ioctl( |
| 40 | + s.fileno(), 0x8927, struct.pack("256s", bytearray(ifname[:15], "utf-8")) |
| 41 | + ) |
| 42 | + return info[18:24] |
| 43 | + |
| 44 | + else: |
| 45 | + |
| 46 | + def get_hw(ifname): |
| 47 | + """Returns a unicode string containing the MAC address of the interface. |
| 48 | +
|
| 49 | + :param ifname: Interface name such as ``wlp2s0`` |
| 50 | + :type ifname: str |
| 51 | + :rtype: str |
| 52 | + """ |
| 53 | + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 54 | + info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack("256s", ifname[:15])) |
| 55 | + return info[18:24] |
38 | 56 |
|
39 | 57 |
|
40 | 58 | def to_str(data, separator=":"): |
|
0 commit comments