Skip to content

Commit a548a6a

Browse files
authored
Merge pull request #6297 from chrisburr/use-psutil-network
[8.0] Use psutil.net_if_addrs for Network.discoverInterfaces
2 parents 0f850c6 + 6e5a1df commit a548a6a

File tree

2 files changed

+9
-34
lines changed

2 files changed

+9
-34
lines changed

src/DIRAC/Core/Utilities/Network.py

Lines changed: 7 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -4,45 +4,19 @@
44
"""
55
import socket
66
import os
7-
import struct
8-
import array
9-
import fcntl
10-
import platform
117
from urllib import parse
128

9+
import psutil
10+
1311
from DIRAC.Core.Utilities.ReturnValues import S_OK, S_ERROR
1412

1513

1614
def discoverInterfaces():
17-
max_possible = 128
18-
maxBytes = max_possible * 32
19-
mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
20-
names = array.array("B", b"\0" * maxBytes)
21-
# 0x8912 SICGIFCONF
22-
fcntlOut = fcntl.ioctl(mySocket.fileno(), 0x8912, struct.pack("iL", maxBytes, names.buffer_info()[0]))
23-
outbytes = struct.unpack("iL", fcntlOut)[0]
24-
namestr = names.tobytes()
25-
26-
if "32" in platform.architecture()[0]:
27-
step = 32
28-
offset = 32
29-
else:
30-
step = 40
31-
offset = 16
32-
33-
ifaces = {}
34-
for i in range(0, outbytes, step):
35-
name = namestr[i : i + offset].split(b"\0", 1)[0].decode()
36-
ip = namestr[i + 20 : i + 24]
37-
ifaces[name] = {"ip": socket.inet_ntoa(ip), "mac": getMACFromInterface(name)}
38-
return ifaces
39-
40-
41-
def getMACFromInterface(ifname):
42-
mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
43-
# bytearray is only needed here for Python 2
44-
info = bytearray(fcntl.ioctl(mySocket.fileno(), 0x8927, struct.pack("256s", ifname[:15].encode())))
45-
return "".join(["%02x:" % char for char in info[18:24]])[:-1]
15+
interfaces = {k: {a.family: a.address for a in v} for k, v in psutil.net_if_addrs().items()}
16+
return {
17+
k: {"ip": v.get(socket.AF_INET, "0.0.0.0"), "mac": v.get(psutil.AF_LINK, "00:00:00:00:00:00")}
18+
for k, v in interfaces.items()
19+
}
4620

4721

4822
def getFQDN():

src/DIRAC/Core/Utilities/test/Test_Network.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
def test_discoverInterfaces():
99
interfaces = discoverInterfaces()
1010
assert len(interfaces) >= 1
11-
assert "lo" in interfaces
11+
assert "lo" in interfaces or "lo0" in interfaces
12+
assert interfaces.get("lo", interfaces.get("lo0"))["ip"].startswith("127")
1213
for interfaceInfo in interfaces.values():
1314
assert "ip" in interfaceInfo
1415
assert "mac" in interfaceInfo

0 commit comments

Comments
 (0)