WinError 10022 error even after socket binding - python

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

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.

Got too many errors in server chat.py in python

It seems i have 2 errors, 1st is that cannot concatenate str and bytes, 2nd is that that the connection was closed by the remote host. Wanna help.
I want that this sends a message to all the clients that this person has left the chat, instead of that it is giving the 2nd answer.
Server_chat.py
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
client.send(bytes("Greetings from the cave! Now type your name and press enter!", "utf8"))
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
def handle_client(client): # Takes client socket as argument.
"""Handles a single client connection."""
name = client.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name
client.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat!" % name
broadcast(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFSIZ).decode('utf8')
if msg != bytes("{quit}", "utf8"):
broadcast(msg, name+": ")
else:
client.send(bytes("{quit}", "utf8"))
client.close()
del clients[client]
broadcast(bytes("%s has left the chat." % name, "utf8"))
break
def broadcast(msg, prefix=""):
for sock in clients:
sock.send(bytes(prefix, "utf8")+msg)
clients = {}
addresses = {}
HOST = '127.0.0.1'
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
client_chat.py
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import tkinter
def receive():
"""Handles receiving of messages."""
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
msg_list.insert(tkinter.END, msg)
except OSError: # Possibly client has left the chat.
break
def send(event=None): # event is passed by binders.
"""Handles sending of messages."""
msg = my_msg.get()
my_msg.set("") # Clears input field.
client_socket.send(bytes(msg, "utf8"))
if msg == "{quit}":
client_socket.close()
top.quit()
def on_closing(event=None):
"""This function is to be called when the window is closed."""
my_msg.set("{quit}")
send()
top = tkinter.Tk()
top.title("Chatter")
messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar() # For the messages to be sent.
my_msg.set("Type your messages here.")
scrollbar = tkinter.Scrollbar(messages_frame) # To navigate through past messages.
# Following will contain the messages.
msg_list = tkinter.Listbox(messages_frame, height=15, width=50, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
msg_list.pack()
messages_frame.pack()
entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()
top.protocol("WM_DELETE_WINDOW", on_closing)
#----Now comes the sockets part----
HOST = '127.0.0.1'
PORT = 33000
if not PORT:
PORT = 33000
else:
PORT = int(PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
tkinter.mainloop()
Error
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
== RESTART: C:\Users\arun.kumar2\Documents\python\chatting app\server_chat.py ==
Waiting for connection...
127.0.0.1:59150 has connected.
127.0.0.1:59176 has connected.
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\arun.kumar2\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\arun.kumar2\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\arun.kumar2\Documents\python\chatting app\server_chat.py", line 28, in handle_client
broadcast(msg, name+": ")
File "C:\Users\arun.kumar2\Documents\python\chatting app\server_chat.py", line 40, in broadcast
sock.send(bytes(prefix, "utf8")+msg)
TypeError: can't concat str to bytes
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Users\arun.kumar2\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\arun.kumar2\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\arun.kumar2\Documents\python\chatting app\server_chat.py", line 26, in handle_client
msg = client.recv(BUFSIZ).decode('utf8')
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
Error is at server_chat.py at line 40
You can't contact string with bytes type so you have to keep them both same type or chnage type of one of them.
def broadcast(msg, prefix=""):
for sock in clients:
sock.send(bytes(prefix+msg, "utf8"))
As the first error said, you cannot concat str (msg) and bytes, so use:
sock.send(bytes(prefix+msg, "utf8"))
Also you should not call bytes(...) on the argument of broadcast() like below:
broadcast(bytes(msg, "utf8"))
Since you have called bytes(...) inside broadcast(). Use below instead:
broadcast(msg)
For the second error, it is because the connection to client is lost but the server is still trying to read from client. You should use try/except to catch the connection lost.
Below is the modified handle_client() and broadcast():
def handle_client(client): # Takes client socket as argument.
"""Handles a single client connection."""
name = client.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name
client.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat!" % name
broadcast(msg) ###
clients[client] = name
while True:
try:
msg = client.recv(BUFSIZ).decode('utf8')
if msg != "{quit}": ###
broadcast(msg, name+": ")
else:
client.send(bytes("{quit}", "utf8"))
break
except (ConnectionResetError, ConnectionAbortedError):
break
client.close()
del clients[client]
broadcast("%s has left the chat." % name) ###
print(name, "disconnected")
def broadcast(msg, prefix=""):
for sock in clients:
sock.send(bytes(prefix+msg, "utf8"))

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...

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

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)

Python Webserver not working

I am building a basic python web server, but I keep having a problem where it is not sending any data (by the way I am accessing the website on the same computer as it is running on and I have the file which the server is trying to access) here is my code:
import socket
HOST, PORT = '', 80
def between(left,right,s):
before,_,a = s.partition(left)
a,_,after = a.partition(right)
return a
filereq = ""
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
lines = []
print("Started!")
listen_socket.listen(1)
print("Listening")
while True:
try:
lines = []
client_connection, client_address = listen_socket.accept()
print("Connected")
request = client_connection.recv(1024)
print("Received Data!")
filereq = between("GET /", " HT", request)
print(filereq)
filereq = open(filereq)
for line in filereq:
lines.append(line)
print(lines)
sendata = ''.join(lines)
print(sendata)
http_response = """\
HTTP/1.1 200 OK
{}
""".format(sendata)
print(http_response)
client_connection.sendall(http_response)
print("Sent the Data!")
client_connection.close()
print("Connection Closed!")
except:
5+5
The problem is that the server is implemented in Python3 but the code mixes bytes and strings, which works in Python2 but not Python3.
This causes an error in the between function, because partition is being called on a bytes object but is being provided with str separator values.
>>> data = b'abc'
>>> data.partition('b')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
To fix this, decode the data from bytes to str when read from the socket, then encode back to bytes before sending the response (socket.sendall expects bytes as an argument).
Also, print out any exceptions that occur so that you can debug them.
import socket
import sys
import traceback
HOST, PORT = '', 80
def between(left,right,s):
before,_,a = s.partition(left)
a,_,after = a.partition(right)
return a
filereq = ""
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
lines = []
print("Started!")
listen_socket.listen(1)
print("Listening")
while True:
try:
lines = []
client_connection, client_address = listen_socket.accept()
print("Connected")
request = client_connection.recv(1024)
print("Received Data!")
# Decode the data before processing.
decoded = request.decode('utf-8')
filereq = between("GET /", " HT", decoded)
print(filereq)
filereq = open(filereq)
for line in filereq:
lines.append(line)
print(lines)
sendata = ''.join(lines)
print(sendata)
http_response = """\
HTTP/1.1 200 OK
{}
""".format(sendata)
print(http_response)
# Encode the response before sending.
encoded = http_response.encode('utf-8')
client_connection.sendall(encoded)
print("Sent the Data!")
client_connection.close()
print("Connection Closed!")
except Exception:
# Print the traceback if there's an error.
traceback.print_exc(file=sys.stderr)

Categories