Skip to content

Instantly share code, notes, and snippets.

@Data5tream
Last active November 6, 2017 22:09
Show Gist options
  • Select an option

  • Save Data5tream/11173466 to your computer and use it in GitHub Desktop.

Select an option

Save Data5tream/11173466 to your computer and use it in GitHub Desktop.
Detect IP Address with Python
#!/usr/bin/env python
# Get correct IP here
def getPublicIP():
data = str(urlopen('http://checkip.dyndns.com/').read())
return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)
def getLocalIP():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8",80))
IP = (s.getsockname()[0])
s.close()
return IP
# Parse commandline arguments
def argparser():
parser = argparse.ArgumentParser(description="IP Address Detector", epilog="(cc) Simon Barth, 2014")
parser.add_argument("-l", "--local", help="Get LAN Address", action="store_true")
global args
args = parser.parse_args()
if args.local == 1:
print getPublicIP()
else:
print getLocalIP()
if __name__ == "__main__":
argparser() # Parse arguments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment