@@ -53,23 +53,28 @@ def find_single_ipv4_address(addrs):
5353 if addr .family == socket .AddressFamily .AF_INET : # IPv4
5454 return addr .address
5555
56-
5756def get_ipv4_address (interface_name = None ):
5857 if_addrs = psutil .net_if_addrs ()
58+ if_stats = psutil .net_if_stats ()
5959
6060 if isinstance (interface_name , str ) and interface_name in if_addrs :
6161 addrs = if_addrs .get (interface_name )
6262 address = find_single_ipv4_address (addrs )
6363 return address if isinstance (address , str ) else ""
6464 else :
65- if_stats = psutil .net_if_stats ()
66- # remove loopback
67- if_stats_filtered = {key : if_stats [key ] for key , stat in if_stats .items () if "loopback" not in stat .flags }
68- # sort interfaces by
69- # 1. Up/Down
70- # 2. Duplex mode (full: 2, half: 1, unknown: 0)
71- if_names_sorted = [stat [0 ] for stat in sorted (if_stats_filtered .items (), key = lambda x : (x [1 ].isup , x [1 ].duplex ), reverse = True )]
72- if_addrs_sorted = OrderedDict ((key , if_addrs [key ]) for key in if_names_sorted if key in if_addrs )
65+ # filter out loopback interfaces based on their address
66+ if_addrs_filtered = {
67+ iface : addrs
68+ for iface , addrs in if_addrs .items ()
69+ if not any (addr .address == '127.0.0.1' for addr in addrs if addr .family == socket .AF_INET )
70+ }
71+
72+ if_names_sorted = [
73+ iface for iface , _ in sorted (if_stats .items (), key = lambda x : (x [1 ].isup , x [1 ].duplex ), reverse = True )
74+ if iface in if_addrs_filtered
75+ ]
76+
77+ if_addrs_sorted = OrderedDict ((iface , if_addrs_filtered [iface ]) for iface in if_names_sorted )
7378
7479 for _ , addrs in if_addrs_sorted .items ():
7580 address = find_single_ipv4_address (addrs )
0 commit comments