How to get local ip address python?

15.3k views Asked by At

There's a code I found in internet that says it gives my machines local network IP address:

hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)

but the IP it returns is 192.168.94.2 but my IP address in WIFI network is actually 192.168.1.107 How can I only get wifi network local IP address with only python? I want it to work for windows,linux and macos.

1

There are 1 answers

4
Mohammed On BEST ANSWER

You can use this code:

import socket
hostname = socket.getfqdn()
print("IP Address:",socket.gethostbyname_ex(hostname)[2][1])

or this to get public ip:

import requests
import json
print(json.loads(requests.get("https://ip.seeip.org/jsonip?").text)["ip"])