How to find the local IP addresses of the host machine in Python

2 Answers

0 votes
import socket

def get_local_ip():
    soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        soc.connect(('255.255.255.255', 1))
        IP = soc.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        soc.close()

    return IP

print(get_local_ip())



'''
run:

127.0.0.1

'''

 



answered Dec 15, 2023 by avibootz
0 votes
import socket

def get_local_ip():
    soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        soc.connect(("8.8.8.8", 80))
        IP = soc.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        soc.close()
        
    return IP

print(get_local_ip())



'''
run:

127.0.0.1

'''

 



answered Dec 15, 2023 by avibootz

Related questions

1 answer 174 views
1 answer 178 views
2 answers 170 views
1 answer 76 views
1 answer 224 views
1 answer 187 views
...