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)
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.
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.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With