0% found this document useful (0 votes)
82 views1 page

Show Local and Internet Ip

This document contains multiple code snippets to programmatically determine a device's IP address in Python. It shows how to get the local IP address using the socket module, get the public IP address by making HTTP requests to external services, and use regular expressions to extract the IP address from the response text.

Uploaded by

Leon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views1 page

Show Local and Internet Ip

This document contains multiple code snippets to programmatically determine a device's IP address in Python. It shows how to get the local IP address using the socket module, get the public IP address by making HTTP requests to external services, and use regular expressions to extract the IP address from the response text.

Uploaded by

Leon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import socket

# Python Program to Get local IP Address


hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 1)) # connect() for UDP doesn't send packets
local_ip_address = s.getsockname()[0]
print(local_ip_address)

import os
print(os.system('ipconfig'))

import socket
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0)
try:
# doesn't even have to be reachable
s.connect(('10.254.254.254', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
print(get_ip())

# Python Program to Get Internet IP Address


import requests, json
data = json.loads(requests.get("http://ip.jsontest.com/").text)
print (data["ip"])

import requests
data = requests.get("http://wikipedia.com").headers
print (data["x-client-ip"])

import requests, re
data = re.search('"([0-9.]*)"',
requests.get("http://ip.jsontest.com/").text).group(1)
print (data)

f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text

from requests import get


get('https://ipapi.co/ip/').text

def get_public_ip():
import re
data = str(requests.get('http://checkip.dyndns.com/').text)
# print(data)
return re.compile(r'Address: (\d+.\d+.\d+.\d+)').search(data).group(1)
public_ip = get_public_ip()
print(public_ip)

You might also like