OSError: [Errno 22] Invalid argument error with simple server class - python

I'm having problems with this very very simple server class, used to run something very similar to this a couple of weeks ago and it worked fine, now i'm getting this error:
root#kali:/tmp# python3 server.py
Traceback (most recent call last):
File "server.py", line 38, in <module>
accept_conns()
File "server.py", line 24, in accept_conns
conn, addr = s.accept()
File "/usr/lib/python3.7/socket.py", line 212, in accept
fd, addr = self._accept()
OSError: [Errno 22] Invalid argument
Code:
import socket
import os
def create_socket():
global s
try:
s = socket.socket()
except socket.error as create_err:
print(create_err)
def bind_socket():
global s
try:
s.bind(("192.168.0.120", 4444))
except socket.error as bind_err:
print(bind_err)
def accept_conns():
global s
conn, addr = s.accept()
print("Connected to: " + addr)
while True:
comm = input("shell> ")
if comm is 'quit':
break
conn.send(comm.encode())
output = conn.recv(2048)
print(output)
create_socket()
bind_socket()
accept_conns()
Any help would be much appreciated

import socket
import os
def create_socket():
s = socket.socket()
return s
def bind_socket(s):
s.bind(("192.168.0.120", 4444))
def accept_conns(s):
s.listen(1)
conn, addr = s.accept()
print("Connected to: ", addr)
while True:
comm = input("shell> ")
if comm is 'quit':
break
conn.send(comm.encode())
output = conn.recv(2048)
print(output)
s = create_socket()
bind_socket(s)
accept_conns(s)

Related

BrokenPipeError: [Errno 32] Broken pipe -- s.send(str(f"{choice}").encode('utf8'))

I'm currently using python to write a simple socket program. However, I have noticed that I'm getting this error sometimes:
Traceback (most recent call last):
File "/Users/user/Desktop/socketpython/client.py", line 41, in <module>
s.send(str(f"{choice}").encode('utf8'))
BrokenPipeError: [Errno 32] Broken pipe
Here is my client code:
#client
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 9999))
while True:
choice = input("Select option: ")
if choice == str(7):
s.send(str(f"{choice}").encode('utf8'))
report = s.recv(2048)
message = report.decode('utf8')
print("** Python DB contents **\n" + message)
And here is my corresponding server code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 9999))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print(f"Connection established from address {addr}")
request = conn.recv(2048).decode("utf-8")
serverdata = request.split(";")
choice = serverdata[0]
if choice == str(7):
sortedList = ""
data.sort()
print(data)
for i in range(len(data)):
sortedList += data[i][0] + "|" + data[i][1] + "|" + data[i][2] + "|" + data[i][3] + "\n"
conn.send(sortedList.encode('utf-8'))
If anyone has any idea on why this problem is happening and what code modifications are necessary to resolve this issue, I would greatly appreciate it.

No attribute to append socket python

I'm creating a simple chat server and when I try to connect a client I get this error:
Traceback (most recent call last):
File "C:\Users\OneDrive\Desktop\Py Files\chat_server.py", line 47, in <module>
recive()
File "C:\Users\OneDrive\Desktop\Py Files\chat_server.py", line 39, in recive
client.append(client)
AttributeError: 'socket' object has no attribute 'append'
Here is my code:
import threading
import socket
host = '127.0.0.1'
port = 20200
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def brodcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
brodcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
brodcast(f'{nickname} left the chat'.encode('ascii'))
nicknames.remove(nickname)
break
def recive():
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
client.send('NICK'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
client.append(client)
print(f'{nickname} joined the chat!')
brodcast(f'{nickname} joined the chat!')
client.send('Connected to the chat')
thread = threading.Thread(target=handle, args=(client,))
thread.start()
recive()
I've provided the code for the server because that is where the error is. On the client end, there appears to be no issues.

lately, I am try to build a client and server to send and receive message and I am stuck

I am just trying to build a basic chat with one client and server. When I run both program they both gave me same error. This error is of client1.py
Traceback (most recent call last):
File "C:/Users/Abishek/AppData/Roaming/JetBrains/PyCharmCE2020.2/scratches/client1.py", line 1, in <module>
from socket import socket, AF_INET, SOCK_STREAM
File "C:\Users\Abishek\AppData\Roaming\JetBrains\PyCharmCE2020.2\scratches\socket.py", line 64, in <module>
IntEnum._convert_(
File "C:\Python37\Lib\enum.py", line 349, in __getattr__
raise AttributeError(name) from None
AttributeError: _convert_
and chatserver.py throw an error as:
Traceback (most recent call last):
File "C:/Users/Abishek/AppData/Roaming/JetBrains/PyCharmCE2020.2/scratches/chatserver.py", line 1, in <module>
from socket import AF_INET,SOCK_STREAM, socket
File "C:\Users\Abishek\AppData\Roaming\JetBrains\PyCharmCE2020.2\scratches\socket.py", line 64, in <module>
IntEnum._convert_(
File "C:\Python37\Lib\enum.py", line 349, in __getattr__
raise AttributeError(name) from None
AttributeError: _convert_
and my code for client1.py is
from socket import socket, AF_INET, SOCK_STREAM
import threading
FORMAT = 'utf-8'
server =input('Enter server ip :')
port = 8080
DISCONNECT_MSG = 'break' or 'disconnect'
sock = socket(AF_INET,SOCK_STREAM)
def connection(server,port):
try:
sock.connect((server, port))
print("Connection successful")
except Exception as err:
print('Connection failed :' +str(err))
def send_msg(client_name):
connected = True
while connected:
message = input('>>> ')
msg = message.encode(FORMAT)
client_info_with_msg = f'[{client_name}: {message}]'
sock.send(client_info_with_msg.encode())
if message == DISCONNECT_MSG:
print(f'{client_name} DISCONNECTED!!')
connected = False
def recv_msg():
run = True
while run:
recv_message = sock.recv(512)
message = recv_message.decode('utf-8')
if message == DISCONNECT_MSG:
run = False
print(f'{message}')
def main(server,port):
connection(server, port)
client_name = input("Enter your name: ")
thread1 = threading.Thread(target=send_msg, args=client_name)
thread1.start()
thread2 = threading.Thread(target=recv_msg, args=None)
thread2.start()
thread1.join()
thread2.join()
sock.close()
main(server,port)
And chatserver.py is:
from socket import AF_INET,SOCK_STREAM, socket
import threading
SERVER = socket.gethostbyname(socket.gethostname())
port = 4444
sock = socket.socket(AF_INET,SOCK_STREAM)
format = 'utf-8'
buffer_size = 128
ADDR = (SERVER,port)
Disconnect_msg = 'Disconnected'
def connection(SERVER,port):
sock.bind(ADDR)
run = True
try:
sock.connect(ADDR)
print('Connection successful')
except Exception as err:
print('Error connecting to client :'+str(err))
run = False
def receiving_data(conn, addr):
connected = True
while connected:
recv_msg = conn.recv(buffer_size).decode(format)
if recv_msg:
print(f"[MESSAGE RECEIVED FROM {conn} {addr}] : {recv_msg}")
if Disconnect_msg in recv_msg:
print(f"[CLIENT {conn} { addr} Disconnected]")
connected= False
if __name__ == '__main__':
sock.bind(ADDR)
sock.listen(5)
print(f'Server ip; {SERVER}')
print('Waiting for connection...')
conn , addr = sock.accept()
accpt_conn = threading.Thread(target=connection, args=ADDR)
recv_data = threading.Thread(target=receiving_data, args =(conn,addr))
recv_data.start()
accpt_conn.start()
recv_data.join()
accpt_conn.join()
sock.close()
Can you please help me what I am doing wrong here.
And I am using Pycharm as my IDE and I am on windows 10.
Thank you everyone...

WinError 10022 error even after socket binding

I've been trying to build a basis for some simple networking, and I keep running into an issue of WinError 10022. Here's my class:
class SocketFactory:
def __init__(self, secret):
self.secret = secret
def send(self, port, e_type, h_type, msg, ip="127.0.0.1"):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("Socket object successfully created.\n")
s.bind((ip, port))
print("Socket bound to port \n")
while True:
c, addr = s.accept()
print('Connection established with ', addr)
if h_type == 1:
header = self.secret
c.send(header, "utf-8")
else:
print("Incorrect header type. Exiting...\n")
exit()
if e_type == 1:
c.send(bytes(msg, "utf-8"))
else:
print("Incorrect encoder type. Exiting...\n")
exit()
c.close()
The preliminary driver code is this:
from sockfactory import SocketFactory
print("Initializing masterserver setup...\n")
port = int(input("Enter port number: \n"))
#ip = str(input("Enter IPv4 address: \n"))
e_type = int(input("The encoding table for outbound bytes will be: \n" "1 = UTF-8 \n"))
h_type = int(input("The immutable header packet type will be: \n" "1 = Simple \n"))
msg = str(input("Enter packet payload: \n"))
secret = b'10000000011000101011110'
SocketFactory.send(port, e_type, h_type, msg, "127.0.0.1")
And the error message:
Traceback (most recent call last):
File "C:/Users/EvESpirit/PycharmProjects/aaa/main", line 13, in <module>
SocketFactory.send(port, e_type, h_type, msg, "127.0.0.1")
File "C:\Users\EvESpirit\PycharmProjects\aaa\sockfactory.py", line 19, in send
self.c, self.addr = s.accept()
File "C:\Users\EvESpirit\AppData\Local\Programs\Python\Python38\lib\socket.py", line 292, in accept
fd, addr = self._accept()
OSError: [WinError 10022] An invalid argument was supplied
Can anyone help me here? What am I doing wrong and how can I do it better? Thank you.
You're missing s.listen() between s.bind() and s.accept():
>>> from socket import *
>>> s=socket()
>>> s.bind(('',5000))
>>> s.accept()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python36\lib\socket.py", line 205, in accept
fd, addr = self._accept()
OSError: [WinError 10022] An invalid argument was supplied
>>> s.listen()
>>> s.accept() # waits here for a connection

Python Thread.start() causes AttributeError

While coding a client-server system in python, I came across a weird error in the server stdout, which shouldn't happen:
Traceback (most recent call last):
File "C:\Users\Adam\Drive\DJdaemon\Server\main.py", line 33, in <module>
ClientThread(csock, addr).start()
AttributeError: 'ClientThread' object has no attribute '_initialized'
I split the line up into multiple lines, and it was start() that caused the error.
Any ideas? Here's the server source code- the client just opens and closes the connection:
import socket, threading
class ClientThread(threading.Thread):
def __init__(self, sock, addr):
self.sock = sock
self.addr = addr
def run(self):
sock = self.sock
addr = self.addr
while True:
msg = sock.recv(1024).decode()
if not msg:
print('Disconnect: ' + addr[0] + ':' + str(addr[1]))
sock.close()
return
# Constants
SERVER_ADDRESS = ('', 25566)
MAX_CLIENTS = 10
MCSRV_ADDRESS = ('localhost', 25567)
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(SERVER_ADDRESS)
srv.listen(MAX_CLIENTS)
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
(csock, addr) = srv.accept()
print('Connect: ' + addr[0] + ':' + str(addr[1]))
ClientThread(csock, addr).start()
You forgot to call ClientThread's parent contructor in __init__.
def __init__(self, sock, addr):
super(ClientThread, self).__init__()
self.sock = sock
self.addr = addr

Categories