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()
Related
I'm trying to write a program that gets IP adress as an input inside a while loop and makes a TCP connection with it.
Here is an example:
import socket
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
adress=input('Enter the IP:')
s1.connect((adress, 8000))
message=input('Enter the message:')
s1.send(message.encode())
s1.close()
Server:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8000))
s.listen(5)
print('ready')
while True:
c, addr = s.accept()
recieved_message= c.recv(1024)
print(recieved_message.decode())
c.close()
It successfully makes the first connection and server recieves the first message but when I try to connect it again by inputting the same IP adress I get this error:
[WinError 10038] an operation was attempted on something that is not a socket
I removed s1.close() to outside of the while loop to fix thix but this time I got this error:
[WinError 10056] A connection attempt targeted an already connected socket
I can't find way to solve this. How can I fix this problem?
The first error is from reusing a closed socket, and the second error is from reconnecting to an already connected socket.
Put the s1 = line inside the while loop in the client to create a new socket for each connection.
import socket
while True:
s1 = socket.socket()
address = input('Enter the IP:')
s1.connect((address, 8000))
message = input('Enter the message:')
s1.send(message.encode())
s1.close()
So i have a server and client program where the two programs communicate with each other.
my problem is when the server disconnects/goes offline the clients program immediately stops running.
how can i make it so the client program keeps running after the server goes off and keeps trying to connect every 20 seconds lets say so when the server goes back online it reconnects. Edit: I forgot to mention I know how to reconnect the main issue is getting the code to keep running instead of stoping when socket disconnects. Also I know for a fact the whole code works. It's If I close the terminal of the server program, then the clients program stops too.
part of client code to reconnect:
import socket
import os
import sys
import subprocess
import time
from time import sleep
s = socket.socket()
host = '192.168.2.16'
port = 9999
connected = False
while connected == False:
try:
s.connect((host,port))
connected = True
except socket.error:
sleep(5)
part of the server code:
import socket
import sys
import os
import threading
import time
from queue import Queue
NUMBER_OF_THREADS = 2
JOB_NUMBER = [1,2]
queue = Queue()
all_connections = []
all_adresses = []
def socket_create():
try:
global s
global host
global port
host = '0.0.0.0'
port = 9999
s = socket.socket()
except socket.error as msg:
print("Error: " + str(msg))
def socket_bind():
try:
global host
global s
global port
print("Binding Socket To Port " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket Binding Error: " + str(msg) + '/n' + "Trying Again...")
socket_bind()
def accept_connections():
for c in all_connections:
c.close()
del all_connections[:]
del all_adresses[:]
while 1:
try:
conn, address = s.accept()
conn.setblocking(1)
all_connections.append(conn)
all_adresses.append(address)
print("\nConnection has been established: " + address[0])
except:
print("Error accepting connections")
and error:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
Simple answer i found.
use try and except. simple as that.
Can you help me with the program now the problem is that when I enter localhost my program cannot find the open port or the closed one, if you really want to help me and you know how to solve it or fix it, please just compile my code separately just for me right now the program for some reason can’t get to receive a message from the host, I searched the entire Internet and can’t find anywhere the scanner has multiple UDP ports
import socket
import sys
# Ask for input
remoteServer = raw_input('Enter a remote host to scan: ')
remoteServerIP = socket.gethostbyname(remoteServer)
print( "-" * 60)
print ('Please wait, scanning remote host', remoteServerIP)
print( "-" * 60)
for port in range(1,1025):
try:
sock=socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
sock.sendto('hello',(remoteServerIP,port))
#sock.settimeout(1)
data, address = sock.recvfrom(1024)
if data != None:
print ('Port {}: Open'.format(port))
else:
print ('Port {}: Closed'.format(port))
sock.close()
except socket.error as sock_err:
if(sock_err.errno == socket.errno.ECONNREFUSED):
print sock_err('Connection refused')
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
except socket.error:
print "Couldn't connect to server"
except KeyboardInterrupt:
print 'You pressed Ctrl+C'
Need to use ICMP packet.For the program to work, you need to enter python
I publish my code because the answer to this question is practically nonexistent and the task is actually difficult.
import socket
import sys
import subprocess
def getServiceName(port, proto):
try:
name = socket.getservbyport(int(port), proto)
except:
return None
return name
UDP_IP = sys.argv[1]
for RPORT in range(int(sys.argv[2]), int(sys.argv[3])):
MESSAGE = "ping"
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
if client == -1:
print("udp socket creation failed")
sock1 = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
if sock1 == -1:
print("icmp socket creation failed")
try:
client.sendto(MESSAGE.encode('utf_8'), (UDP_IP, RPORT))
sock1.settimeout(1)
data, addr = sock1.recvfrom(1024)
except socket.timeout:
serv = getServiceName(RPORT, 'udp')
if not serv:
pass
else:
print('Port {}: Open'.format(RPORT))
except socket.error as sock_err:
if (sock_err.errno == socket.errno.ECONNREFUSED):
print(sock_err('Connection refused'))
client.close()
sock1.close()
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 am currently working on a server in Python, the problem I am facing is the client could not retrieve the sent data from server.
The code of the server is:
import sys
import socket
from threading import Thread
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(1024)
print rm
try:
self.sockfd.sendall("\n Test text to check send.")
print "Data send successfull"
break
except socket.error, e:
print "Could not send data"
break
except ValueError:
self.sockfd.send("\n Could not connect properly")
def run(self):
self.newClientConnect()
self.sockfd.close()
while True:
buff = self.sockfd.recv(1024)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '127.0.0.1'
PORT = 80
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
print ("Server Started")
try:
serversocket.bind(('',5000))
except ValueError,e:
print e
serversocket.listen(5)
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
#--
And the client connecting is:
import socket
HOST = '192.168.1.4' # The remote host
PORT = 5000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
s.close()
print 'Received', data#repr(data)
In need of a quick solution....
Thanks,
I tested out your code, and when I commented out
rm= self.sockfd.recv(1024)
print rm
it worked fine. Basically the server stopped there to wait for a message that never came. If it still does not work for you, there might be two problems. Either you have a firewall that blocks the connection somehow, or you have old servers running in the background from previous tries that actually wasn't killed. Check your processes if pythonw.exe or equivalent is running when it shouldn't be, and kill it.
To wait for response:
with s.makefile('rb') as f:
data = f.read() # block until the whole response is read
s.close()
There are multiple issues in your code:
nested while True without break
finally: ..close() is executed before except ValueError: ..send
multiple self.sockfd.close()
etc
Also you should probably use .sendall() instead of .send().
your server code is excepting client send something first,
rm= self.sockfd.recv(1024)
but I don't see any in your code
please try send something in your client code
s.connect((HOST, PORT))
s.send("hello")
Short solution
Add a short sleep after connect.
import time
time.sleep(3)