0

I'm using following function in my script. It checks outside IP with urlopen but if the timeout occurs skip to another site until you get IP and than return it...

Not sure if this is the optimal way though.. if its not possible to get ip at all, it will reboots the eth, but that part is not important...

def current_ip():
    url_list = ['http://ipecho.net/plain', 'http://ipinfo.io/ip', 'http://icanhazip.com']
    for i in url_list:
        try:
            sleep(3)
            my_ip = urlopen(i, timeout=5).read()
            logging.info('Getting actual IP from: %s ', i)
            break
        except:
            logging.error('Could not get IP from: %s ', i)
            my_ip = 'error'
            continue

    if my_ip == 'error':
        logging.error('Could not get outside IP at all...')
        restart_interface()
        logging.debug('Restarted eth...')
        sleep(3)
        my_ip = current_ip()

    return my_ip.rstrip()
VladoPortos
  • 563
  • 5
  • 21

0 Answers0