Skip to content

Commit

Permalink
#3930 use standard library
Browse files Browse the repository at this point in the history
  • Loading branch information
totaam committed Jul 30, 2023
1 parent abfee70 commit 3586fcc
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 58 deletions.
14 changes: 1 addition & 13 deletions tests/unittests/unit/net/net_util_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
get_info, get_interfaces, get_interfaces_addresses, #get_interface,
get_gateways, get_bind_IPs, do_get_bind_ifacemask,
get_ssl_info, get_interface,
if_nametoindex, if_indextoname, get_iface,
get_iface,
get_free_tcp_port,
)
from unit.test_util import silence_error
Expand All @@ -29,15 +29,6 @@ def test_netifaces(self):
return
ip_ifaces = defaultdict(list)
for iface in ifaces:
if if_nametoindex:
try:
i = if_nametoindex(iface)
except Exception:
pass
else:
if if_indextoname:
assert if_indextoname(i)==iface, "expected interface %s for index %i but got %s" % (
iface, i, if_indextoname(i))
ipmasks = do_get_bind_ifacemask(iface)
for ip, _ in ipmasks:
ip_ifaces[ip].append(iface)
Expand All @@ -54,9 +45,6 @@ def test_netifaces(self):
get_ssl_info()
get_info()

if if_indextoname:
assert if_indextoname(-1) is None

def invalid_iface(s):
v = get_iface(s)
if v:
Expand Down
8 changes: 5 additions & 3 deletions xpra/client/gtk3/sessions_gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
)
from xpra.gtk_common.gobject_compat import register_os_signals
from xpra.net.common import DEFAULT_PORTS
from xpra.net.net_util import if_indextoname
from xpra.util import typedict
from xpra.os_util import bytestostr, WIN32
from xpra.log import Logger
Expand Down Expand Up @@ -349,9 +348,12 @@ def get_uri(self, password, interface, protocol, name:str, stype:str, domain, ho
if display and display.startswith(":"):
dstr = display[1:]
#append interface to IPv6 host URI for link local addresses ("fe80:"):
if interface and if_indextoname and address.lower().startswith("fe80:"):
if interface and address.lower().startswith("fe80:"):
#ie: "fe80::c1:ac45:7351:ea69%eth1"
address += "%%%s" % if_indextoname(interface)
try:
address += "%%%s" % socket.if_indextoname(interface)
except OSError:
pass
if username:
if password:
uri = "%s://%s:%s@%s" % (mode, username, password, address)
Expand Down
10 changes: 7 additions & 3 deletions xpra/net/mdns/avahi_publisher.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import avahi # @UnresolvedImport
import dbus
from socket import if_nametoindex, if_indextoname
try:
from dbus.exceptions import DBusException
except ImportError:
Expand All @@ -16,7 +17,7 @@

from xpra.net.mdns import XPRA_TCP_MDNS_TYPE, XPRA_UDP_MDNS_TYPE, SHOW_INTERFACE
from xpra.dbus.common import init_system_bus
from xpra.net.net_util import get_iface, if_nametoindex, if_indextoname
from xpra.net.net_util import get_iface
from xpra.log import Logger

log = Logger("network", "mdns")
Expand Down Expand Up @@ -65,9 +66,12 @@ def __init__(self, listen_on, service_name:str, service_type:str=XPRA_TCP_MDNS_T
iface_index = get_interface_index(host)
log("iface_index(%s)=%s", host, iface_index)
td = text_dict or {}
if SHOW_INTERFACE and if_indextoname and iface_index is not None:
if SHOW_INTERFACE and iface_index is not None:
td = text_dict.copy()
td["iface"] = if_indextoname(iface_index)
try:
td["iface"] = if_indextoname(iface_index)
except OSError:
pass
txt = []
if text_dict:
for k,v in td.items():
Expand Down
43 changes: 10 additions & 33 deletions xpra/net/net_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

# taken from the code I wrote for winswitch

import os
import socket
import sys
from typing import Any, Callable
Expand Down Expand Up @@ -165,13 +166,12 @@ def get_iface(ip) -> str:
return ""
if ip.find("%")>=0:
iface = ip.split("%", 1)[1]
if if_nametoindex:
try:
if_nametoindex(iface)
except OSError:
return ""
else:
return iface
try:
socket.if_nametoindex(iface)
except OSError:
return ""
else:
return iface
ipv6 = ip.find(":")>=0
af = socket.AF_INET6 if ipv6 else socket.AF_INET
ipchars = ".:0123456789"
Expand Down Expand Up @@ -248,29 +248,6 @@ def get_iface(ip) -> str:
return best_match


# Found this recipe here:
# http://code.activestate.com/recipes/442490/
if_nametoindex = None
if_indextoname = None

if WIN32: # pragma: no cover
def int_if_nametoindex(iface):
#IPv6 addresses give us the interface as a string:
#fe80:....%11, so try to convert "11" into 11
try:
return int(iface)
except (TypeError, ValueError):
return None
if_nametoindex = int_if_nametoindex
else:
if_nametoindex = socket.if_nametoindex
def socket_if_indextoname(index):
if index<0:
return None
return socket.if_indextoname(index)
if_indextoname = socket_if_indextoname


net_sys_config : dict[str,Any] = {}
def get_net_sys_config() -> dict[str,Any]:
global net_sys_config
Expand Down Expand Up @@ -461,9 +438,9 @@ def main(): # pragma: no cover
print("Network interfaces found:")
netifaces = import_netifaces()
for iface in get_interfaces():
if if_nametoindex:
print("* %s (index=%s)" % (iface.ljust(20), if_nametoindex(iface)))
else:
try:
print("* %s (index=%s)" % (iface.ljust(20), socket.if_nametoindex(iface)))
except OSError:
print(f"* {iface}")
addresses = netifaces.ifaddresses(iface) #@UndefinedVariable pylint: disable=no-member
for addr, defs in addresses.items():
Expand Down
7 changes: 4 additions & 3 deletions xpra/platform/netdev_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ def print_iface(iface):
def main():
# pylint: disable=import-outside-toplevel
import sys
from xpra.net.net_util import get_interfaces, if_nametoindex
from xpra.net.net_util import get_interfaces
from socket import if_nametoindex
from xpra.platform import program_context
from xpra.log import Logger, enable_color, add_debug_category, enable_debug_for
log = Logger("network")
Expand All @@ -73,9 +74,9 @@ def main():

print("Network interfaces found:")
for iface in get_interfaces():
if if_nametoindex:
try:
print("* %s (index=%s)" % (iface.ljust(20), if_nametoindex(iface)))
else:
except OSError:
print(f"* {iface}")
print_iface(iface)

Expand Down
8 changes: 5 additions & 3 deletions xpra/scripts/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3098,7 +3098,6 @@ def run_list_mdns(error_cb, extra_args) -> int:
listener_class = Zeroconflistener
except ImportError:
error_cb("sorry, 'list-mdns' requires an mdns module")
from xpra.net.net_util import if_indextoname
from xpra.dbus.common import loop_init
from gi.repository import GLib # @UnresolvedImport
loop_init()
Expand Down Expand Up @@ -3135,8 +3134,11 @@ def show_new_found():
def mdns_add(interface, _protocol, name, _stype, domain, host, address, port, text):
text = typedict(text or {})
iface = interface
if if_indextoname and iface is not None:
iface = if_indextoname(interface)
if iface is not None:
try:
iface = socket.if_indextoname(interface)
except OSError:
pass
username = text.strget("username", "")
uq = text.strget("uuid", str(len(found))), username, host
found.setdefault(uq, []).append((iface or "", name, domain, host, address, port, text))
Expand Down

0 comments on commit 3586fcc

Please sign in to comment.