Skip to content

Commit 5d48881

Browse files
juliangilbeyJulian Gilbeyminrk
authored
Support psutil for finding network addresses (#1033)
* Support psutil * remove unneeded type: ignore --------- Co-authored-by: Julian Gilbey <[email protected]> Co-authored-by: Min RK <[email protected]>
1 parent 7716291 commit 5d48881

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

jupyter_client/localinterfaces.py

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,35 @@ def _load_ips_ipconfig() -> None:
151151
_populate_from_list(addrs)
152152

153153

154+
def _load_ips_psutil() -> None:
155+
"""load ip addresses with netifaces"""
156+
import psutil
157+
158+
global LOCALHOST
159+
local_ips = []
160+
public_ips = []
161+
162+
# dict of iface_name: address_list, eg
163+
# {"lo": [snicaddr(family=<AddressFamily.AF_INET>, address="127.0.0.1",
164+
# ...), snicaddr(family=<AddressFamily.AF_INET6>, ...)]}
165+
for iface, ifaddresses in psutil.net_if_addrs().items():
166+
for address_data in ifaddresses:
167+
if address_data.family == socket.AF_INET:
168+
addr = address_data.address
169+
if not (iface.startswith("lo") or addr.startswith("127.")):
170+
public_ips.append(addr)
171+
elif not LOCALHOST:
172+
LOCALHOST = addr
173+
local_ips.append(addr)
174+
if not LOCALHOST:
175+
# we never found a loopback interface (can this ever happen?), assume common default
176+
LOCALHOST = "127.0.0.1"
177+
local_ips.insert(0, LOCALHOST)
178+
local_ips.extend(["0.0.0.0", ""]) # noqa
179+
LOCAL_IPS[:] = _uniq_stable(local_ips)
180+
PUBLIC_IPS[:] = _uniq_stable(public_ips)
181+
182+
154183
def _load_ips_netifaces() -> None:
155184
"""load ip addresses with netifaces"""
156185
import netifaces # type: ignore[import-not-found]
@@ -227,13 +256,20 @@ def _load_ips(suppress_exceptions: bool = True) -> None:
227256
228257
This function will only ever be called once.
229258
230-
It will use netifaces to do it quickly if available.
259+
If will use psutil to do it quickly if available.
260+
If not, it will use netifaces to do it quickly if available.
231261
Then it will fallback on parsing the output of ifconfig / ip addr / ipconfig, as appropriate.
232262
Finally, it will fallback on socket.gethostbyname_ex, which can be slow.
233263
"""
234264

235265
try:
236-
# first priority, use netifaces
266+
# first priority, use psutil
267+
try:
268+
return _load_ips_psutil()
269+
except ImportError:
270+
pass
271+
272+
# second priority, use netifaces
237273
try:
238274
return _load_ips_netifaces()
239275
except ImportError:

0 commit comments

Comments
 (0)