Reputation: 1501
I'm trying to make a simple port scanner using python but it seems that it hangs duringrecv
that the default timeout raise an exception and terminate the program.
import socket, argparse
parser = argparse.ArgumentParser(description="A Port scanner",
usage="command -w <website> -p <port>",
prog="Port Scanner")
parser.add_argument("-w", nargs=1, type=str, required=True, dest="site",
help="The website to scan")
parser.add_argument("-p", nargs=1, type=int, dest="port",
help="The port to scan", default=80)
namespace = parser.parse_args()
def connect(host: str, port:int) -> bool:
ip = socket.gethostbyname(host)
socket.setdefaulttimeout(10)
conn_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
conn_sock.connect((ip, port))
except:
print("[+] port {} is closed".format(port))
return False
else:
print("[+] Port {} is open".format(port))
conn_sock.sendall(b"HTTP GET /")
response = conn_sock.recv(100)
print("[+] Got 100 bytes as {}".format(response))
return True
connect(namespace.site[0], namespace.port[0])
running as prog -w www.google.com -p 80
(also tried with different websites) it says that port 80 is opened and connected as supposed also sending data doesn't seem to cause any problem. Trackback is
response = conn_sock.recv(100)
socket.timeout: timed out
Upvotes: 0
Views: 59
Reputation: 87074
The server is not responding because you have not sent it a complete or valid request. Try:
conn_sock.sendall(b"HTTP GET /\r\n\r\n")
A blank line is required between the (optional) headers and the (optional) body. You don't set any headers so you simply need two CRLFs at the end of the request. This will get you communicating with the server.
But you should change your request to:
GET / HTTP/1.1\r\n\r\n
if you want to get a valid HTTP/1.1 200 OK
response.
Upvotes: 1