'Connection refused' with sockets - python

Client The code has been written in Python.
Client
import socket
host = '192.168.0.118'
#host = ''
port = 5560
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
while True:
command = input("Enter your command")
if command == 'EXIT':
s.send(str.ecode(command))
break
elif command == 'KILL':
s.send(str.encode(command))
break
s.send(str.encode(command))
reply = s.recv(1024)
print(reply.decode('utf-8'))
s.close()
Server
import socket
host = ''
port = 5560
storedValue = "You man I done"
def setupServer():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print("yes Created")
try:
s.bind((host,port))
except socket.error as msg:
print(msg)
print("socket bind complet")
return s
def setupConnection():
s.listen(1)
conn,address = s.accept()
print("done connection: " + address[0] + ":" + str(adress[1]))
return conn
def GET():
reply = storedValue
return reply
def REPEAT (dataMessage):
reply = dataMessage[1]
return reply
def dataTransfer(conn):
while True:
data = conn.recv(1024)
data = data.decode('utf-8')
dataMessage = data.split(' ', 1)
command = dataMessage[0]
if command == 'GET':
reply = GET()
elif command == 'Repeat':
reply = REPEAT(dataMessage)
elif command == 'EXIT':
print("our client has left us")
break
elif command == 'KILL':
print("Shut down")
s.close()
break
else:
reply = 'Unknown Command'
conn.sendall(str.encode(reply))
print("Data has been sent")
conn.close()#
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
break
Error I got this
Traceback (most recent call last):
File "cookieClient.py", line 8, in <module>
s.connect((host,port))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused

Related

TCP chat in Python 3.9 - ConnectionAbortedError: [WinError 10053]

i am creating a private chat server and client with python 3.9, it was working perfectly until i decided to add an admin user with a password and the ability to kick and ban other users.
Now when i start the server and try to login from the client the server crashes and shows me this error: ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
I tried to turn off the firewall and any anti-virus softwares but nothing solved my problem, my network configuration has not changed since i created the original program.
here there is the server code:
import socket
import threading
import time
host = '127.0.0.1'
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
msg = message = client.recv(1024)
if msg.decode('ascii').startswith('KICK'):
if nicknames[client.index(client)] == 'admin':
name_to_kick = msg.decode('ascii')[5:]
kick_user(name_to_kick)
else:
client.send('Bel tentativo...'.encode('ascii'))
elif msg.decode('ascii').startswith('BAN'):
if nicknames[client.index(client)] == 'admin':
name_to_ban = msg.decode('ascii')[4:]
kick_user(name_to_ban)
with open('bans.txt', 'a') as f:
f.write(f'{name_to_ban}\n')
print(f'{name_to_ban} bannato!')
else:
client.send('Bel tentativo...'.encode('ascii'))
else:
broadcast(message)
except:
if client in clients:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast('{} uscito dalla chat!'.format(nickname).encode('ascii'))
nicknames.remove(nickname)
break
def receive():
while True:
client, address = server.accept()
print("---------------------------------------")
print("Connesso con {}".format(str(address)))
client.send('NICK'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
with open('bans.txt', 'r') as f:
bans = f.readlines()
if nickname+'\n' in bans:
clients.send('BAN'.encode('ascii'))
client.close()
continue
if nickname == 'admin':
client.send('PASS'.encode('ascii'))
password = client.recv(1024).decode('ascii')
if password != 'password':
client.send('REFUSE'.encode('ascii'))
client.close()
continue
nicknames.append(nickname)
clients.append(client)
print("Nickname: {}".format(nickname))
client.send('Connesso al server!'.encode('ascii'))
client.send("-------------------------------------".encode('ascii'))
time.sleep(0.5)
broadcast("{} entrato in chat!".format(nickname).encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
def kick_user(name):
if name in nicknames:
name_index = nicknames.index(name)
client_to_kick = clients[name_index]
clients.remove(client_to_kick)
client_to_kick.send('Sei stato buttato fuori!'.encode('ascii'))
client_to_kick.close()
nicknames.remove(name)
broadcast(f'{name} buttato fuori!'.encode('ascii'))
print("Ascoltando...")
receive()
and here the client:
import socket
import threading
print("-------------------------------------")
nickname = input("Scegli il tuo nickname: ")
if nickname == 'admin':
password = input("Inserisci la password: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 55555))
stop_thread = False
def receive():
while True:
global stop_thread
if stop_thread:
break
try:
message = client.recv(1024).decode('ascii')
if message == 'NICK':
client.send(nickname.encode('ascii'))
next_message = client.serv(1024).decode('ascii')
if next_message == 'PASS':
client.send(password.encode('ascii'))
if client.rect(1024).decode('ascii') == 'REFUSE':
print("Password sbagliata!")
stop_thread = True
elif next_message == 'BAN':
print('Connessione negata, sei bannato!')
client.close()
stop_thread = True
else:
print(message)
except:
print("Errore!")
client.close()
break
def write():
while True:
if stop_thread:
break
message = f'{nickname}: {input("")}'
if message[len(nickname)+2:].startswith('/'):
if nickname == 'admin':
if message[len(nickname)+2:].startswith('/kick'):
client.send(f'KICK {message[len(nickname)+2+6:]}'.encode('ascii'))
elif message[len(nickname)+2:].startswith('/ban'):
client.send(f'BAN {message[len(nickname)+2+5:]}'.encode('ascii'))
else:
print("Comandi accessibili solo a admin!")
else:
client.send(message.encode('ascii'))
receive_thread = threading.Thread(target=receive)
receive_thread.start()
write_thread = threading.Thread(target=write)
write_thread.start()
Do somebody know what could be my problem?
Thanks

Python Sockets: Send data, then receive response and finally send confirmation

I'm not sure if this is allowed, but I would like to have the client send a notification, receive a response and then finally send back a final validation message. The first send and receive seems to work fine, but the final .sendall() doesn't seem to send to the server.
Client:
import threading
import time
import socket
import sys
alarm_on = False # Flag to stop the thread
# The thread function
def beep():
while alarm_on:
print("BEEP BEEP BEEP")
time.sleep(20)
try:
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create Movement Socket")
mysock.connect(('1.1.1.1',1234))
try:
mysock.sendall(b'MOVEMENT')
except socket.error:
print("Failed to send")
sys.exit()
#Recieve command to turn ignore, turn on alarm, or turn off alarm
try:
command = mysock.recv(10000)
print(command)
except socket.error:
print("Error receiving data")
sys.exit()
print("Command is: " + str(command))
#Turn on command
if command == b'ON':
state = command
alarm_on = True
# Start the thread
thrd1 = threading.Thread(target=beep).start()
mysock.sendall(state) # ********Final Validation to server of state
#Ignore the movement for 30 min
elif command == b'NO':
state = b'Silent for 15 min'
print(state)
mysock.sendall(state) # ********Final Validation to server of state
time.sleep(900)
Server
import socket
import sys
try:
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create socket")
sys.exit
try:
mysock.bind(("",1234))
except:
print("Failed to bind")
mysock.listen(5)
while True:
validation = False
conn,addr = mysock.accept()
data = conn.recv(1000)
print("Data recieved: " + str(data))
if data == b'MOVEMENT':
while not validation:
command = input("Movement detected, type ON enable Alarm or NO to ignore: ")
command = command.upper()
if command == "ON" :
message = command
validation = True
elif command == "NO":
message = command
validation = True
else:
print("Data is: " + str(data) + "is not a valid input")
sys.exit()
try:
conn.sendall(bytes(message.encode()))
except:
print("Failed to send")
sys.exit()
conn.close()
mysock.close()
Can you do a final send after an initial send and receive? If so, why isn't my last sendall working?
In order to receive the second message, a second .recv() needs to be established to catch the "validation message". I added the following line to the server code:
validation = conn.recv(1000)
print(validation)
The full server code:
import socket
import sys
try:
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create socket")
sys.exit
try:
mysock.bind(("",1234))
except:
print("Failed to bind")
mysock.listen(5)
while True:
validation = False
conn,addr = mysock.accept()
data = conn.recv(1000)
print("Data recieved: " + str(data))
if data == b'MOVEMENT':
while not validation:
command = input("Movement detected, type ON enable Alarm or NO to ignore: ")
command = command.upper()
if command == "ON" :
message = command
validation = True
elif command == "NO":
message = command
validation = True
else:
print("Data is: " + str(data) + "is not a valid input")
sys.exit()
try:
conn.sendall(bytes(message.encode()))
except:
print("Failed to send")
sys.exit()
validation = conn.recv(1000)
print(validation)
conn.close()
mysock.close()

Simple TELNET Server

I have written a telnet server and client, but I don't receive a response from the server and I don't know where the problem is.
SERVER
import socket
import subprocess
def handle_client(client_socket):
MAX_RECV_BUFFER = 1024
allowed_commands = ["ls, cd, ls -l"]
recv_size = 1
while recv_size:
data_buffer = client_socket.recv(MAX_RECV_BUFFER)
command = data_buffer.decode("utf-8")
if not data_buffer:
print("Client just disconected")
break
recv_size = len(data_buffer)
if command in allowed_commands:
response = run_command(commad)
client_socket.send(response.encode("utf-8"))
data_buffer = ""
def init_server(server_address, reuseAddr=True):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server_socket.bind(server_address)
except socket.error as serr:
print(str(serr))
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, "SO_REUSEPORT"):
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
server_socket.listen(5)
print("Server listen at {}:{}".format(server_address[0], server_address[1]))
try:
while True:
client_socket, client_address = server_socket.accept()
print("Client has connected {}:{}".format(client_address[0], client_address[1]))
handle_client(client_socket)
except KeyboardInterrupt as kerr:
print("Server is closing...")
client_socket.close()
server_socket.close()
def run_command(commad):
try:
output = subprocess.check_output(commad, stderr=subprocess.STDOUT,
shell=True)
except OSError as oserr:
return output
if __name__ == "__main__":
init_server(("127.0.0.1",8080))
CLIENT
import socket
def init_client(server_address):
connected = True
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Connecting {} to server ...'.format(server_address))
client_socket.connect(server_address)
while connected:
# allowed__commands = ['ls, cd, ls-l']
try:
if server_address[0] == '127.0.0.1':
message = input('\nlocalhost#localhost' + '>> ')
else:
message = input(server_address[0] + '#' + server_address[1] +
'>> \n')
print('Sending message: {}'.format(message))
client_socket.sendall(message.encode('utf-8'))
recv_data(client_socket)
except IOError as e:
print('Error: {}'.format(e))
except Exception as e:
print('Other error: {}'.format(e))
except KeyboardInterrupt:
connected = False
def recv_data(client_socket):
recv_size = 1
MAX_RECV_BUFFER = 1024
while recv_size:
data_buffer = client_socket.recv(MAX_RECV_BUFFER)
message = data_buffer.decode('utf-8')
print('Received data: '.format(message))
if not data_buffer:
break
recv_size += len(data_buffer)
data_buffer = ''
client_socket.close()
if __name__ == '__main__':
init_client(('127.0.0.1', 8080))

How to make the server side socket code run continuously

I have a server/client socket program that is used to transfer a file from the client to the server. The issue is that the code stops running once the file is transferred. I want to change it such that the server side code is continuously running so that I can transfer a file multiple times without having to run the code again and again
Server code:
import socket
host = ''
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind comlete.")
return s
def setupConnection():
s.listen(1) # Allows one connection at a time.
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def storeFile(filePath):
picFile = open(filePath, 'wb')
print(filePath)
print("Opened the file.")
pic = conn.recv(1024)
#print(pic)
while pic:
print("Receiving picture still.")
picFile.write(pic)
pic = conn.recv(1024)
picFile.close()
def dataTransfer(conn):
# A big loop that sends/receives data until told not to.
while True:
# Receive the data
data = conn.recv(1024) # receive the data
data = data.decode('utf-8')
# Split the data such that you separate the command
# from the rest of the data.
dataMessage = data.split(' ', 1)
command = dataMessage[0]
if command == 'GET':
reply = GET()
elif command == 'REPEAT':
reply = REPEAT(dataMessage)
elif command == 'STORE':
print("Store command received. Time to save a picture")
storeFile(dataMessage[1])
reply = "File stored."
elif command == 'LED_ON':
callLED()
reply = 'LED was on'
else:
reply = 'Unknown Command'
# Send the reply back to the client
conn.sendall(str.encode(reply))
#print("Data has been sent!")
conn.close()
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
break
The client side code is below:
import socket
from time import sleep
from time import time
host = '192.168.0.17'
port = 5560
data = "hi"
filepath = "/var/www/html/unknown.txt"
def setupSocket():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s
def sendPic(s, filePath):
print(filePath)
pic = open(filePath, 'rb')
chunk = pic.read(1024)
s.send(str.encode("STORE " + filePath))
t = time()
while chunk:
print("Sending Picture")
s.send(chunk)
#print(chunk)
chunk = pic.read(1024)
pic.close()
print("Done sending")
print("Elapsed time = " + str(time() - t) + 's')
#s.close()
return "Done sending"
def sendReceive(s, message):
s.send(str.encode(message))
reply = s.recv(1024)
print("We have received a reply")
print("Send closing message.")
s.send(str.encode("EXIT"))
#s.close()
reply = reply.decode('utf-8')
return reply
def transmit(message):
s = setupSocket()
response = sendReceive(s, message)
return response
def backup(filePath):
s = setupSocket()
response = sendPic(s, filePath)
return response
while True:
backup(filepath)
print("Backup Complete!")
break
I do not own the code. I have made some change to the code that I got from a YouTube video.
Have you had a look at the SocketServer module?
You could setup your dataTransfer() function as the handle() method of a RequestHandler class, then start your server with the serve_forever() method.

Sending contents of file to server - python socket

When doing the put command I am getting this error. I can't seem to figure out why.
line 41, in
data = client.recv(1024)
error: [Errno 10053] An established connection was aborted by the software in your host machine
Here is my client code:
import socket
import sys
import os
HOST = 'localhost'
PORT = 8082
size = 1024
def ls():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(userInput)
result = s.recv(size)
print result
s.close()
return
def put(command):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(command)
string = command.split(' ', 1)
input_file = string[1]
with open(input_file, 'rb') as file_to_put:
for data in file_to_put:
s.sendall(data)
s.close()
return
def get(command):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(command)
string = command.split(' ', 1)
input_file = string[1]
with open(input_file, 'wb') as file_to_get:
while True:
data = s.recv(1024)
print data
if not data:
break
file_to_get.write(data)
file_to_get.close()
s.close()
return
done = False
while not done:
userInput = raw_input()
if "quit" == userInput:
done = True
elif "ls" == userInput:
ls()
else:
string = userInput.split(' ', 1)
if (string[0] == 'put'):
put(userInput)
elif (string[0] == 'get'):
get(userInput)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.close()
print "Closing connection."
And server code:
import socket
import os
import sys
host = ''
port = 8082
backlog = 5
size = 1024
serverID = socket.gethostbyname(socket.gethostname())
info = 'SERVER ID: {} port: {}'.format(serverID, port)
print info
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
done = False
#Loop until client sends 'quit' to server
while not done:
client, address = s.accept()
data = client.recv(size)
print "Server received: ", data
if data:
client.send("Server Says... " + data)
if data == "quit":
done = True
elif data == "ls":
data = os.listdir('c:\\') # listing contents of c: drive
client.send(str(data))
print data
else:
string = data.split(' ', 1)
data_file = string[1]
if (string[0] == 'put'):
with open(data_file, 'wb') as file_to_write: # opening sent filename to write bytes
while True:
data = client.recv(1024)
if not data:
break
file_to_write.write(data) # writing data
file_to_write.close() # closing file
break
print 'Receive Successful'
elif (string[0] == 'get'):
with open('C:\\' + data_file, 'rb') as file_to_send:
for data in file_to_send:
client.send(data)
print 'Send Successful'
client.close()
s.close()
print "Server exiting."

Categories