Following the code from here I have got an IP address checker. However instead of outputting an IP address it outputs []. Code:
import urllib.request
import re
print("we will try to open this url, in order to get IP Address")
url = "http://checkip.dyndns.org"
print(url)
request = urllib.request.urlopen(url).read()
theIP = re.findall(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}", request.decode('utf-8'))
print("your IP Address is: ", theIP)
Expected output:
we will try to open this url, in order to get IP Address
http://checkip.dyndns.org
your IP Address is: 40.74.89.185
The IP address there is not mine and comes from HERE.
Real output:
we will try to open this url, in order to get IP Address
http://checkip.dyndns.org
your IP Address is: []
I have just copied from the website and then fixed the errors. What have I done wrong. Help please...
My python version is idle 3.8.
Turns out that your regex where wrong:
I've updated the code and using requests get:
findall will return a list of elements since you are get only one ip back just use [0]
from requests import get
import re
iphtml = get('http://checkip.dyndns.org').text
theIP = re.findall( r'[0-9]+(?:\.[0-9]+){3}', iphtml)
print(f"Your IP is: {theIP[0]}")
Your code updated:
import urllib.request
import re
print("we will try to open this url, in order to get IP Address")
url = "http://checkip.dyndns.org"
print(url)
request = urllib.request.urlopen(url).read()
theIP = re.findall(r'[0-9]+(?:\.[0-9]+){3}', request.decode('utf-8'))
print("your IP Address is: ", theIP[0])
Related
Soo... Long story short, I'm trying to get the IP-Addresses of Links which can cause extrem harm to other Users on Discord (also known as Account Scam Links, Account Token Grabber Links, etc. etc.). [If you may have any concern about my IP-Address being grabbed, I'm using a VPN, so it won't help them this much] I've searched up on how to save the response which comes from the Request after it's printing The IP Address of xyz.com is <IP-Address>.
After some tries I've decided to ask the so called "all-knowing stackoverflow Community" to help me out on my Problem.
import socket
with open("suspicious_links.txt", 'r') as f:
while True:
hostname = f.read()
# IP lookup from hostname
with open("log.txt", 'a') as e:
try:
e.write(f"The {hostname}'s IP Address is {socket.gethostbyname(hostname)}\n")
print(f'The {hostname} IP Address is {socket.gethostbyname(hostname)}')
except socket.gaierror:
print(f"Searching up {hostname} has failed. Perhaps this Website doesn't exist anymore!")
The Problem:
The actual IP-Address doesn't show up, it's just telling me 0.0.0.0, the issue of the {hostname} variable initialized at line 5 doesn't seem to have an effect since the hostname is left blank.
The expected Output:
I expected the Code to print out the IP Address of the Hosts so I could further investigate and maybe contact the legal owners of the hosts for those Websites to inform them about
this malicious behaviour.
Thanks for reading in advance
Greetings
Ohnezahn ZAE
Your problem is you incorrectly reading file line by line. I suppose you need something like this:
import socket
with open("suspicious_links.txt", 'r') as f:
hostnames = [line.rstrip() for line in f]
for hostname in hostnames:
# IP lookup from hostname
with open("log.txt", 'a') as e:
try:
e.write(f"The {hostname}'s IP Address is {socket.gethostbyname(hostname)}\n")
print(f'The {hostname} IP Address is {socket.gethostbyname(hostname)}')
except socket.gaierror:
print(f"Searching up {hostname} has failed. Perhaps this Website doesn't exist anymore!")
If you suspicious_links.txt will be, for example:
stackoverflow.com
youtube.com
google.com
then output will be:
The stackoverflow.com's IP Address is 151.101.65.69
The youtube.com's IP Address is 216.58.215.110
The google.com's IP Address is 172.217.16.46
This is what should be happening
>>> socket.gethostbyname('')
'0.0.0.0'
then verify your hostname is not None or empty before querying.
I have a list of cidr notations and i have a python program that generates a list of ip adress from the cidr notation.Here is the program
from netaddr import IPNetwork
for ip in IPNetwork('104.24.0.0/6'):
print ('%s' % ip)
But i want to make the program loop through each of the ip adress and send http requests then search for some specific status code and if it finds the required status code it should return which ip adress has that status code
Try this:
import requests
from netaddr import IPNetwork
required_status_code = 200 # your required status code goes here
for ip in IPNetwork('104.24.0.0/6'):
resp = requests.get(f'http://{ip}')
if resp.status_code == requires_status_code:
print (f'ip {ip} matches required status code!')
import socket
import os
url = input("enter website:")
a = socket.gethostbyname(url)
print(a)
os.system('ping '+ a)
I have that code above but when i run it the IP address that i get from the socket.gethostbyname(url) it doesn't resolve to the website that i gave it.
Most of the websites give me a error 403.
am i missing something? any tips?
I am crawling through the ARIN whois API to find all network ranges. The code below takes a starting IP address, sends it to ARIN, and returns the ending IP address of that network. That ending address is then incremented by one, and this new value becomes the next address sent to ARIN. This works well, but it is inefficient when ISPs have swaths of unassigned addresses because each starting address has to be checked until another assigned network is found.
The code is a self-contained example that shows how there are a few network ranges assigned, and then a period of addresses that are unassigned by AT&T. How should these unassigned networks be checked without checking each and every address?
import requests
from ipaddress import ip_address
IPAddress = str.replace('12.31.71.56','.','-')
while True:
try:
url = 'https://whois.arin.net/rest/net/NET-' + IPAddress + '-1.json'
request = requests.get(url)
response = request.json()
endAddress = response['net']['endAddress']['$']
IPAddress = str.replace((ip_address(endAddress) + 1).compressed,'.','-')
print(IPAddress)
print(response['net']['orgRef']['#name'])
except ValueError:
IPAddress = str.replace(IPAddress,'-','.')
IPAddress = str.replace((ip_address(IPAddress) + 1).compressed,'.','-')
print(IPAddress)
if IPAddress == '12-31-71-150':
break
When I call socket.getsockname() on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?
This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.
The only way I can think of that's guaranteed to give it to you is to hit a service like http://whatismyip.com/ to get it.
https://github.com/bobeirasa/mini-scripts/blob/master/externalip.py
'''
Finds your external IP address
'''
import urllib
import re
def get_ip():
group = re.compile(u'(?P<ip>\d+\.\d+\.\d+\.\d+)').search(urllib.URLopener().open('http://jsonip.com/').read()).groupdict()
return group['ip']
if __name__ == '__main__':
print get_ip()
You'll need to use an external system to do this.
DuckDuckGo's IP answer will give you exactly what you want, and in JSON!
import requests
def detect_public_ip():
try:
# Use a get request for api.duckduckgo.com
raw = requests.get('https://api.duckduckgo.com/?q=ip&format=json')
# load the request as json, look for Answer.
# split on spaces, find the 5th index ( as it starts at 0 ), which is the IP address
answer = raw.json()["Answer"].split()[4]
# if there are any connection issues, error out
except Exception as e:
return 'Error: {0}'.format(e)
# otherwise, return answer
else:
return answer
public_ip = detect_public_ip()
print(public_ip)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("msn.com",80))
s.getsockname()
print (urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read())
The most simple method of getting a public IP is by using this
import requests
IP = requests.get('https://api.ipify.org/').text
print(f'Your IP is: {IP}')
Using the address suggested in the source of http://whatismyip.com
import urllib
def get_my_ip_address():
whatismyip = 'http://www.whatismyip.com/automation/n09230945.asp'
return urllib.urlopen(whatismyip).readlines()[0]
You need to make connection to an external Server And Get Your Public IP From The Response
like this:
import requests
myPublic_IP = requests.get("http://wtfismyip.com/text").text.strip()
print("\n[+] My Public IP: "+ myPublic_IP+"\n")