Created
February 6, 2018 03:31
-
-
Save metametadata/15f5a7d1c94cd3fcc6143d2bad16208e to your computer and use it in GitHub Desktop.
Cross-platform local IP detection.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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