Skip to content

Instantly share code, notes, and snippets.

@metametadata
Created February 6, 2018 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metametadata/15f5a7d1c94cd3fcc6143d2bad16208e to your computer and use it in GitHub Desktop.
Save metametadata/15f5a7d1c94cd3fcc6143d2bad16208e to your computer and use it in GitHub Desktop.
Cross-platform local IP detection.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Prints the machine's IP address.
# Inspired by https://stackoverflow.com/a/28950776/4839573. Tested in Linux and MacOS.
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# Doesn't even have to be reachable.
s.connect(('10.255.255.255', 1))
ip = s.getsockname()[0]
except:
ip = '127.0.0.1'
finally:
s.close()
sys.stdout.write(ip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment