@@ -151,6 +151,35 @@ def _load_ips_ipconfig() -> None:
151
151
_populate_from_list (addrs )
152
152
153
153
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
+
154
183
def _load_ips_netifaces () -> None :
155
184
"""load ip addresses with netifaces"""
156
185
import netifaces # type: ignore[import-not-found]
@@ -227,13 +256,20 @@ def _load_ips(suppress_exceptions: bool = True) -> None:
227
256
228
257
This function will only ever be called once.
229
258
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.
231
261
Then it will fallback on parsing the output of ifconfig / ip addr / ipconfig, as appropriate.
232
262
Finally, it will fallback on socket.gethostbyname_ex, which can be slow.
233
263
"""
234
264
235
265
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
237
273
try :
238
274
return _load_ips_netifaces ()
239
275
except ImportError :
0 commit comments