Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a machine's external IP address with Python

Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x

import os
import urllib2

def check_in():

    fqn = os.uname()[1]
    ext_ip = urllib2.urlopen('http://whatismyip.org').read()
    print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)
like image 413
cit Avatar asked Feb 22 '10 14:02

cit


People also ask

Can you get someones IP with Python?

Use the socket. getsockname() Funtion to Get the Local IP Address in Python. If the computer device has a route connected to the Internet, then we can use the getsockname() function. It returns the IP address and port in the form of a tuple.

How do I get external IP?

Type "ipconfig" in the command prompt window and take note of the IP address displayed. If you have multiple network ports in use, like an Ethernet port and a Wi-Fi adaptor, you may see more than one. On a macOS or Linux system, you can use the similarly named "ifconfig" command line tool for the same purpose.


2 Answers

I liked the http://ipify.org. They even provide Python code for using their API.

# This example requires the requests library be installed.  You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/
from requests import get

ip = get('https://api.ipify.org').content.decode('utf8')
print('My public IP address is: {}'.format(ip))
like image 73
Sergiy Ostrovsky Avatar answered Oct 18 '22 21:10

Sergiy Ostrovsky


Python3, using nothing else but the standard library

As mentioned before, one can use an external service like ident.me in order to discover the external IP address of your router.

Here is how it is done with python3, using nothing else but the standard library:

import urllib.request

external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')

print(external_ip)

Both IPv4 and IPv6 addresses can be returned, based on availability and client preference; use https://v4.ident.me/ for IPv4 only, or https://v6.ident.me/ for IPv6 only.

like image 89
Serge Stroobandt Avatar answered Oct 18 '22 22:10

Serge Stroobandt