I'm using python 3.8, and trying to learn to code for networking; I've seen some examples from 2014 with code for a port scanner, which is defines the port scanning function like this:
def pscan(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
con = sock.connect((target, port))
with print_lock:
print("Port:",port,"is open.")
con.shutdown()
con.close()
When I implement this in pycharm I see the message:
"Cannot find reference 'shutdown' in 'None'
and
"Cannot find reference 'close' in 'None'
The code runs, but never seems to stop... I am guessing that it is due to not properly closing the socket.
Can anyone educate me as to where my error is?
connect doesn't return anything.
I think you want this:
def pscan(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((target, port))
with print_lock:
print("Port:",port,"is open.")
sock.shutdown()
sock.close()
Also, no need to call shutdown if you're going to immediately call close afterwards.
Related
def main(port):
try:
ip = '192.168.0.51'
s = socket.socket()
socket.setdefaulttimeout(1)
s.connect((ip, port))
rec = s.recv(1024).decode('utf-8')
print(rec)
except Exception:
pass
for port in range(1,100):
main(port)
I have watched tutorials on this and it still has not worked for me, I also tried it with my public IP but obviously I didn't put that in the code shown. I didn't receive any data from the connection, so I tried to decode it but still didn't work. I am trying to get the banner so the service running on the port. How would I do this? What did I do wrong? I don't mind if it's in py2 or py3
When I run this code I am getting this socket error:
[WinError 10038] An operation was attempted on something that is not a socket
but even if I delete the s.close() it gives me wrong results.
It is a port scanner that are going to try connecting to all ports on the server I want to scan. And the ones that i'm getting connection from is stored in a list. But for some reason it is giving me wrong results. can someone please help me.
import socket
import threading
def scan_for_open_ports():
#Creating variables
OpenPorts = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input('Host to scan: ')
global port
global OpenPorts
port = 1
#Scanning
for i in range(65534):
try:
s.connect((host, port))
s.shutdown(2)
OpenPorts.append(port)
print(str(port) + 'is open.')
s.close()
port += 1
except socket.error as msg:
print(msg)
s.close()
show_user()
def show_user():
#Giving the user results
print('------Open porst-----\n')
print(OpenPorts)
That's because you're closing your socket inside the loop with s.close() and you're not opening it again and you try to connect with a socket that's closed already. you should close the socket when you're done with it at the end of the loop, i also amended your code to make OpenPorts global and remove the unnecessary port variable you define and increment inside your for loop
import socket
OpenPorts = []
def scan_for_open_ports():
# Creating variables
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input('Host to scan: ')
# Scanning
for port in range(1, 65534):
try:
s.connect((host, port))
OpenPorts.append(port)
print(str(port) + 'is open.')
except socket.error as msg:
print(msg)
s.close()
show_user()
def show_user():
# Giving the user results
print('------Open ports-----\n')
print(OpenPorts)
scan_for_open_ports()
I am trying to create a script that will, on error, attempt to reconnect again. But even after the receiving server has been started it still will not connect
send_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try: #Cant get it to make connection after retrying
send_sock.connect((ip, port)) #always throws Con Refused when tryed
break
except socket.error:
print "Connection Failed, Retrying.."
time.sleep(1)
send_sock.send("hi")
edit: Corrected "try:" typo
Had this same issue myself, once I had worked it out it was actually quite a simple solution, all you need to do is create the send_sock before every connection attempt. Not sure why this fixes it but it does for me. Hope it does for you too.
while True:
try:#moved this line here
send_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
send_sock.connect((ip, port)) #no longer throws error
break
except socket.error:
print "Connection Failed, Retrying.."
time.sleep(1)
send_sock.send("hi")
Python socket will give you a error that should help with debugging your problem. For your example.
try:
send_sock.connect((ip, port))
except socket.error as error:
print("Connection Failed **BECAUSE:** {}").format(error)
Second of all you should almost never use while true: [...] as its just going to cause all sorts of problems. In this case you could put in a counter and loop on that break after X attempts.
While counter < 100:
try:
send_sock.connect((ip, port))
except socket.error as error:
print("Connection Failed **BECAUSE:** {}").format(error)
print("Attempt {} of 100").format(counter)
counter += 1
Check out the Python Docs on socket exceptions for more info.
I'm writing a IRC bot in Python.
Source: http://pastebin.com/gBrzMFmA ( sorry for pastebin, i don't know how to efficently/correctly use the code tagthing on here )
When the "irc" socket dies, is there anyway I could go about detecting if its dead and then automatically reconnecting?
I was googling for awhile now and found that I would have to create a new socket. I was trying and added stuff like catching socket.error in the while True: but it seems to just hang and not reconnect correctly..
Thanks for help in advance
Answered here: Python : Check if IRC connection is lost (PING PONG?)
While the question owner's accepted answer works, I prefer John Ledbetter's answer here, soley for its simplicity: https://stackoverflow.com/a/6853352/625919
So, for me, I have something along the lines of
def connect():
global irc
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((server, port))
#and nick, pass, and join stuffs
connect()
while True:
data = irc.recv(4096)
if len(data) == 0:
print "Disconnected!"
connect()
This is the code for Re-Connect socket
import socket
import time
username = "Manivannan"
host = socket.gethostname()
port = 12345 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connected = False
print("Server not connected")
while True:
if(not connected):
try:
s.connect((host, port))
print("Server connected")
connected = True
except:
pass
else:
try:
s.sendall(username.encode('utf-8'))
except:
print("Server not connected")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connected = False
pass
time.sleep(5)
s.close()
I'm trying to translate this from Ruby to Python.
Ruby code:
def read_byte
begin
Timeout.timeout(0.5) do
b = socket.read 1
end
rescue Timeout::Error => e
socket.write("\n")
socket.flush
retry
end
end
def socket
#socket ||= TCPSocket.open #host, #port
rescue SocketError
# TODO: raise a specific error
raise "Unable to open connection to #{#host} with given parameters"
end
My mean problem here is with
socket.flush
I can't find a way to do flush. what other way can I do this?
I wrote this.
Python code:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
s.settimeout(0.5)
while True:
try:
print s.recv(1)
except socket.timeout:
s.sendall("\n")
I doubt that flushing the socket will make a difference, but here is a way to "flush" the socket by first creating a file-like object.
def flush_socket(s):
f = s.makefile()
f.flush()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
s.settimeout(0.5)
while True:
try:
print s.recv(1)
except socket.timeout:
s.sendall("\n")
flush_socket(s)
The stream is kinda hanging with my code.
Of course it is, since it is an endless loop unless some exception other than socket.timeout occurs.
maybe it's another part of the ruby code
It must be ... Inspect the Ruby loop where read_byte is called and compare that to your Python while True.