Get local IP address for our adaptor

import socket

#******************************************
#******************************************
#********** GET LOCAL IP ADDRESS **********
#******************************************
#******************************************
def get_local_ip():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    try:
        sock.connect(('10.255.255.255', 1))     #Doesn't neeed to be a reachable IP address
        local_ip = sock.getsockname()[0]
    except Exception:
        local_ip = '127.0.0.1'
    finally:
        sock.close()

    return local_ip
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *