4

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.

soroushamdg
  • 191
  • 1
  • 2
  • 14
  • Does this answer your question? [Finding local IP addresses using Python's stdlib](https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib) – Alexandru Dinu Oct 14 '20 at 08:04
  • No, actually I've tried it too, but it also gives me the wrong IP address. – soroushamdg Oct 14 '20 at 16:44

2 Answers2

8

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"])
Mohammed
  • 127
  • 3
  • 9
0

Here's code from the whatismyip Python module that can grab it from public websites:

import urllib.request

IP_WEBSITES = (
           'https://ipinfo.io/ip',
           'https://ipecho.net/plain',
           'https://api.ipify.org',
           'https://ipaddr.site',
           'https://icanhazip.com',
           'https://ident.me',
           'https://curlmyip.net',
           )

def getIp():
    for ipWebsite in IP_WEBSITES:
        try:
            response = urllib.request.urlopen(ipWebsite)

            charsets = response.info().get_charsets()
            if len(charsets) == 0 or charsets[0] is None:
                charset = 'utf-8'  # Use utf-8 by default
            else:
                charset = charsets[0]

            userIp = response.read().decode(charset).strip()

            return userIp
        except:
            pass  # Network error, just continue on to next website.

    # Either all of the websites are down or returned invalid response
    # (unlikely) or you are disconnected from the internet.
    return None

print(getIp())

Or you can install pip install whatismyip and then call whatismyip.whatismyip().

Al Sweigart
  • 11,566
  • 10
  • 64
  • 92