Last active
December 7, 2017 09:39
-
-
Save zhanglongqi/acc07eda0a02cefea9e5 to your computer and use it in GitHub Desktop.
Get ip v4 address on OS X or Linux using python and ip command
This file contains hidden or 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
| from subprocess import check_output | |
| import sys | |
| import re | |
| if sys.platform == 'darwin': | |
| ip0 = check_output(['ip', 'addr', 'show', 'en0']) | |
| else: | |
| ip0 = check_output(['ip', 'addr', 'show', 'eth0']) | |
| ip1 = re.search('inet\s.*(?=/)', str(ip0)) | |
| ip2 = re.search('\d+\.\d+\.\d+\.\d+', str(ip1.group())) | |
| ip = ip2.group() | |
| print(ip0, ip1, ip2, ip, sep='\n') | |
| """ | |
| b'en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500\n\tether 6c:40:08:bc:64:7c\n\tinet6 fe80::6e40:8ff:febc:647c/64 scopeid 0x4\n\tinet 192.168.8.100/24 brd 192.168.8.255 en0\n' | |
| <_sre.SRE_Match object; span=(152, 170), match='inet 192.168.8.100'> | |
| <_sre.SRE_Match object; span=(5, 18), match='192.168.8.100'> | |
| 192.168.8.100 | |
| """ |
This file contains hidden or 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
| # Thanks https://www.chenyudong.com/archives/python-get-local-ip-graceful.html | |
| import socket | |
| def get_host_ip(): | |
| try: | |
| s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
| s.connect(('8.8.8.8', 80)) | |
| ip = s.getsockname()[0] | |
| finally: | |
| s.close() | |
| return ip |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment