I have this problem with a portscanner which keeps hanging at scanning port 1. How can I solve this problem?
#! /usr/bin/env python
import socket
import subprocess
from datetime import datetime
#Clear the screen
subprocess.call('clear', shell=True)
def portscan():
server = raw_input("Enter the server to scan: ")
serverIP = socket.gethostbyname(server)
# Printing banner with information about host
print "[+] Host: {} [+]\nIP Address: {}\n".format(server, serverIP)
print "[!] Please wait, scanning for open services...\n"
#Time when scan started.
t1 = datetime.now()
try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((serverIP, port))
if result == 0:
print "[+] Port {}: Status:OPEN\n".format(result)
sock.close()
except socket.gaierror:
print "Hostname could not be resolved, Exiting...\n"
sys.exit()
except socket.error:
print "Couldn\'t connect to server, Exiting\n"
sys.exit()
#Checking time again
t2 = datetime.now()
#Calculate duration of scan
totaltime = t2 - t1
print "Scan completed, duration: {}\n".format(totaltime)
What happens when i run it i give it a hostname and resolve it to a IP
Address but whenever the scan starts it keeps scanning port 1 as i saw
in Wireshark
I think that you maybe need a timeout.
Eventually, your sock.connect_ex( ), will to raise an exception socket.error: [Errno 110] Connection timed out, as you can read more about it, in this answer.
But the default timeout could be 120 seconds, and maybe you don't want to wait so much. So, you can set your own timeout, like that:
try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10) #timeout set for wait up 10 seconds.
result = sock.connect_ex((serverIP, port))
sock.settimeout(None)
To know why to use sock.settimeout(None), and see another ways of setting timeout, you can read this discussion.
I'm not sure if it was what you're looking for, but I hope it may help.
Related
I captured packets on individual text files with tcpdump, I want to send back the captured packets, first I extracted the IP and Port, but I have not been able to send the packet.
This is my code:
def client():
packet = open("packet3.txt", "r")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(("192.168.128.1", 80))
while True:
try:
sock.send("packet")
sleep(1)
reply = sock.recv(131072)
if not reply:
break
print "recvd: ", reply
except KeyboardInterrupt:
print "bye"
break
sock.close()
return
client()
I get this error:
reply = sock.recv(131072)
error: [Errno 10054] An existing connection was forcibly closed by the remote host
I am wondering why my portScanner module runs and claims that all my ports are closed?
I am running Python 2.7 because thats what Violent Python(the book) uses.
Only solution I have tried so far was I have set my DNS to 8.8.8.8 and secondary to 8.8.4.4 because my socket takes 'www.google.com' as the Ip.
Code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverIp = socket.gethostbyname('www.google.com')
def pscan(port):
try:
s.connect((serverIp,port))
return True
except:
return False
for x in range(1,101):
if pscan(x):
print("Port %d is open!!!" % (x))
else:
print("Port %d is closed" % (x))
You only create a single socket and try to use it in multiple connect's. This is not possible. If you look at the details of the Exception you will notice that the first one (port 1) fails slowly because the connect timed out but the following ones all fail quickly because of "Operation already in progress".
The fix is to create a new socket before each connect. Additionally it might be helpful to reduce the time it tries to connect with s.settimeout(1).
I am trying to establish a simple UDP connection using Python code, between 2 PCs through internet.
Code run on PC_1:
import socket
import time
HOST = "ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
code run on the 2nd PC:
import socket
HOST = "ip_address_of_PC1"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)
While running the code on 2nd PC am getting following error message:
return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context
change print s.recv(30) to:
data, addr = s.recvfrom(30)
print data
and in the 2nd PC code, the HOST variable needs the value of the 2nd PC ip, not the first one:
HOST = "ip_address_of_PC2"
Code run on PC1:
import socket
import time
HOST = "public ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
Code run on PC2:
import socket
HOST = "private ip_address_of_PC2"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)
I am trying to send some data from my python client to python server
I have followed this link
My python client code is as follows
#Socket client example in python
import socket #for sockets
import sys #for exit
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
host = '10.4.1.25';
port = 80;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
s.connect((host , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
message = "16973"
try :
#Set the whole string
s.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
#Now receive data
reply = s.recv(4096)
print reply
the python server code is
import socket
import sys
HOST = '' # Symbolic name meaning all available interfaces
PORT = 80 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#now keep talking with the client
data = conn.recv(1024)
conn.sendall(data)
conn.close()
s.close()
The Function sendall is used to send data to client , means when I enter the text in terminal on server I should see it on client as well. But this does not happen
The output which I get is
Server Output
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 10.4.1.255:44656
Client Output
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
I am unable to know what's going wrong here?
Also how can I send data (message) from Python Client to Python server??
Any help would be great !
Thanks!
There is a server for a single client. Client can connect and disconnect at any time
Here is simplified code
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while true:
a = s.accept()
try:
data = a[0].recv(1024)
except socket.error:
a[0].close()
print 'cought the error'
It works, but socket.error generation takes random amount of time from few seconds up to a minute. May this value be managed?
If the client disconnects, there is no socket.error, rather recv() returns an empty string immediately. Besides, you are not closing the connection in this case.