diff --git a/hpbandster/utils.py b/hpbandster/utils.py index e29a25d..df192ce 100644 --- a/hpbandster/utils.py +++ b/hpbandster/utils.py @@ -11,11 +11,30 @@ -def nic_name_to_host(nic_name): - """ translates the name of a network card into a valid host name""" - from netifaces import ifaddresses, AF_INET - host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr'] - return(host) +def nic_name_to_host(nic_name=None): + """ translates the name of a network card into a valid host name""" + from netifaces import ifaddresses, AF_INET + + def get_nic_name_from_system(): + import re + import subprocess + process = subprocess.Popen("ip route get 8.8.8.8".split(), + stdout=subprocess.PIPE) + output = process.stdout.read().decode() + s = re.search(r'dev\s*(\S+)', output) + return s.group(1) + + # if the network card name is not a valid one an ecxeption will be raised + # and the method get_nic_name_from_system will discover a valid card name + try: + host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr'] + # ValueError if the nic_name is no correct + # TypeError is nic_name is None + except (ValueError, TypeError) as e: + nic_name = get_nic_name_from_system() + host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr'] + + return(host)