Hi all
In the ‘port scanner’ project, we are asked to print a string with the URL and IP address of the website we are scanning.
As you can see in the image below, sometimes we are given the IP address and sometimes the URL.
Converting a URL into an IP address is easy, we just need to use the line:
target = "www.freecodecamp.org"
target_ip = socket.gethostbyname(target)
But it seems that converting an IP address into a URL is hard. I think I found a solution online which is this:
from dns import resolver,reversename
addr = reversename.from_address(target_ip)
target_URL = str(resolver.query(addr,"PTR")[0])
But I am unable to install dnspython in my computer for some reason
My question is: is there an easier way of doing this? Is using dnspython the only way? How have others done this in their own project?
Thanks for your time
Jaime
Your code so far
import socket
import re
def get_open_ports(*arg):
if len(arg) == 2:
target = arg[0]
port_range = arg[1]
verbose = False
elif len(arg) == 3:
target = arg[0]
port_range = arg[1]
verbose = arg[2]
if re.findall(r'\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b', target):
target_ip = target
from dns import resolver,reversename
addr = reversename.from_address(target_ip)
target_URL = str(resolver.query(addr,"PTR")[0])
print(target_URL)
else:
target_ip = socket.gethostbyname(target)
target_URL = target
open_ports = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for i in range(port_range[0], port_range[1], 1):
if s.connect_ex((target_ip, i)):
continue
else:
open_ports.append(i)
return_string = open_ports
if verbose:
line1 = 'Open ports for ' + target_URL + ' (' + target_ip + ')'
return_string = f"{line1}\n"
return return_string
get_open_ports("137.74.187.100", [442,445], True)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36
Challenge: Port Scanner
Link to the challenge: