IP address does not always resolve with socket.gethostbyname - python

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?

Related

IP Address and Hostname doesn't show up while trying to retrieve and save it in a file

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.

How can i get http requests in python 3 and have the program sort the status codes

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!')

Ip address checker doesn't output IP address

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])

IP address by Domain Name

I am trying to get IP address of a domain..
i am using following code
>> import socket
>> socket.gethostbyname('www.google.com')
its giving me following error..
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
socket.gethostbyname('www.google.com')
gaierror: [Errno 11001] getaddrinfo failed
what is wrong with my code...is there any other way to get ip address by domain name in python..???
please help...
Your code is correct.
Perhaps you have a firewall in between you and these servers that is blocking the request?
import socket
domainName = input('Enter the domain name: ')
print(socket.gethostbyname(domainName))
I think you forgot to print it because it works for me.
# Python3 code to display hostname and
# IP address
# Importing socket library
import socket
# Function to display hostname and
# IP address
def get_Host_name_IP():
try:
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
print("Hostname : ",host_name)
print("IP : ",host_ip)
except:
print("Unable to get Hostname and IP")
# Driver code
get_Host_name_IP() #Function call
#This code is conributed by "Sharad_Bhardwaj".
That error also appears when the domain is not hosted anywhere (is not connected to any IP, any nameserver) or simply does not exist.
Here is full example, how you can get IP address by Domain Name.
import urllib.parse
import socket
import dns.resolver
def get_ip(target):
try:
print(socket.gethostbyname(target))
except socket.gaierror:
res = head(target, allow_redirects=True)
try:
print(r.headers['Host'])
except KeyError:
parsed_url = urllib.parse.urlparse(target)
hostname = parsed_url.hostname
try:
answers = dns.resolver.query(hostname, 'A')
for rdata in answers:
print(rdata.address)
except dns.resolver.NXDOMAIN:
print('ip not found')
get_ip('example.com')

How do I get the external IP of a socket in Python?

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")

Categories