OSError: [WinError 10022] An invalid argument was supplied Python - python

I have written a client and a server-side code to set a P2P type system with a server as a middleman to distribute a file to N clients.
I am getting this error OSError: [WinError 10022] An invalid argument was supplied in this chunk of my code on the server side
try:
for i in l:
print(i)
x = random.randint(0,N-1)
print(x,"Index")
serverSocketTCPRequest = serverSocketTCPList[x]
serverSocketTCPRequest.settimeout(2)
serverSocketTCPRequest.connect((i[0],i[1]))
serverSocketTCPRequest.send("SEND".encode())
serverSocketTCPRequest.send(str(chunkID).encode())
data = serverSocketTCPRequest.recv(1024)
serverSocketTCPRequest.close()
b = False
return data
except Exception as ex:
print(traceback.format_exc())
time.sleep(1)
# print(l)
pass
I am getting the following error:
Traceback (most recent call last):
File "d:\IITD\5th Sem\COL334\Assignment 2\server.py", line 149, in getChunks
serverSocketTCPRequest.connect((i[0],i[1]))
OSError: [WinError 10022] An invalid argument was supplied
Traceback (most recent call last):
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\IITD\5th Sem\COL334\Assignment 2\server.py", line 198, in sendChunkRequest
checkMessage, serverAddress = serverSocketUDPRequest.recvfrom(1024)
socket. Timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\IITD\5th Sem\COL334\Assignment 2\server.py", line 149, in getChunks
serverSocketTCPRequest.connect((i[0],i[1]))
OSError: [WinError 10022] An invalid argument was supplied
My client side code for the same is
def handleTCP(client:Client):
global N
while(True):
try:
# print(clientList.index(client), client.clientSocketTCPRequest.getsockname())
client.clientSocketTCPRequest.listen(2*N)
client.clientSocketTCPRequest.settimeout(2)
connectionSocket, addr = client.clientSocketTCPRequest.accept()
print("Connected")
message = connectionSocket.recv(1024).decode()
if message.decode() == "SEND":
i = connectionSocket.recv(1024).decode()
connectionSocket.send(client.dict[int(i)])
connectionSocket.close()
elif message.decode() == "GET":
i = connectionSocket.recv(1024).decode()
client.dict[int(i)] = connectionSocket.recv(1024)
connectionSocket.close()
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
m = template.format(type(ex).__name__, ex.args)
print(m,client.clientSocketTCPRequest.getsockname())
# print(traceback.format_exc())
continue
I can't think of a reason this is occurring. The client side shows just a timeout error on each of the N ports.
I have attached the entire client and server side codes and the file I'm trying to send.

Related

MySQL and Python Connector Test Errors

I am connecting, or trying to, MySQL and Python via PyCharm and I input the code that I was given and I am getting several errors that I am unable to resolve. Is there a pro out there that can assist?
Here is the code:
import mysql.connector
from mysql.connector import errorcode
config = {
"user": "movies_user",
"password": "popcorn",
"host": "127.0.0.1",
"database": "movies",
"raise on warnings": True
}
try:
db = mysql.connector.connect(**config)
print("\n Database user {} connected to MySQL on host {} with database {}".format(config["user"], config["host"],
config["database"]))
input("\n\n Press any key to continue...")
except mysql.connector as Error:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print(" The supplied username or password are invalid")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print(" The supplied database does not exist")
else:
print(err)
finally:
db.close()
And here are the errors:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 353, in config
DEFAULT_CONFIGURATION[key]
KeyError: 'raise on warnings'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 14, in <module>
db = mysql.connector.connect(**config)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\__init__.py", line 159, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 129, in __init__
self.connect(**kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 449, in connect
self.config(**kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 355, in config
raise AttributeError("Unsupported argument '{0}'".format(key))
AttributeError: Unsupported argument 'raise on warnings'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 20, in <module>
except mysql.connector as Error:
TypeError: catching classes that do not inherit from BaseException is not allowed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 30, in <module>
db.close()
NameError: name 'db' is not defined
Process finished with exit code 1
I feel like I have tried everything that I can possibly find on Google. Any help is much appreciated!
I have tried the above code and I have tried resolving the errors to no avail.

Python Socket Server - Kick Function

I'm trying to kick client from the server, and after that I get the follwing exception:
Exception in thread Thread-2 (__handle_client):
Traceback (most recent call last):
File "/Users/macbook/Desktop/Python Projects/Cars/Server/server.py", line 36, in __handle_client
message = client.recv(1024).decode(FORMAT)
OSError: [Errno 9] Bad file descriptor
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1009, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 946, in run
self._target(*self._args, **self._kwargs)
File "/Users/macbook/Desktop/Python Projects/Cars/Server/server.py", line 41, in __handle_client
client.send('You left the chat room'.encode(FORMAT))
OSError: [Errno 9] Bad file descriptor.
But when I use the exit function it is going well. Both using the __close_connection function.
This is my Code:
def __handle_client(self,client):
while True:
try:
message = client.recv(1024).decode(FORMAT)
if self.__handle_messsage(message,client) == True:
break
except:
client.send('You left the chat room'.encode(FORMAT))
self.__broadcast(f'{self.__clientnick[client]} has left the chat room!',)
del self.__clientnick[client]
client.close()
break
def __handle_messsage(self,message,client):
if message == '/exit':
exit_message = 'You have discinnected successfully.'
self.__close_connction(exit_message,client)
return True
if message.startswith('/kick'):
if self.__clientnick.get(client) == 'admin':
for check_client in self.__clientnick:
if self.__clientnick.get(check_client) == message[6:len(message)]:
kick_message = 'You have been kicket from the chat room.'
self.__close_connction(kick_message,check_client)
return True
else:
client.send('You are not admin!'.encode(FORMAT))
def __close_connection(self,message,client):
client.send(message.encode(FORMAT))
self.__broadcast(f'{self.__clientnick[client]} has left the chat room!',client)
del self.__clientnick[client]
client.close()
It seems that you already closed the connection when you did kick and that is why you get the exception. the second exception is when you try to send a message to the closed connection.

How to send an error message being printed in an exception case by email to a user?

I am using Python3.7
I am trying to email an error in the except condition to the user if the code is not working and following is my code:
except Exception as e:
logging.basicConfig(filename='logfile.log',format='%(asctime)s %(message)s',filemode='w')
logger=logging.getLogger()
logger.setLevel(logging.ERROR)
logger.error(e)
print("ERROR MESSAGE",e)
MY_ADDRESS = '*****#gmail.com'
PASSWORD = '*******'
MY_ADDRESS1 = '****#gmail.com'
s = smtplib.SMTP(host='smtp.gmail.com', port=***)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
print("login")
msg = MIMEMultipart() # create a message
msg['From']=MY_ADDRESS
msg['To']=MY_ADDRESS1
msg['Subject']="ERROR MESSAGE"
message="ERROR"
msg.attach.as_string(MIMEText(e))
print("ERROR MAILED")
s.send_message(msg)
s.quit()
I want to send the error message in variable 'e' which is being printed
But I am unable to do so
Following is the error:
This is the error which i want to print and mail:
ERROR MESSAGE [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'
This is the error shown on the python shell:
Traceback (most recent call last):
File "C:\Python37\Sopan.py", line 30, in <module>
wb.save(workbook_name)
File "C:\Python37\lib\site-packages\openpyxl\workbook\workbook.py", line 408, in save
save_workbook(self, filename)
File "C:\Python37\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
File "C:\Python37\lib\zipfile.py", line 1207, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python37\Sopan.py", line 88, in <module>
msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python37\Sopan.py", line 88, in <module>
msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'
How do i send the error message being printed in variable 'e' by email to someone
THANK YOU
The logging module itself has smtp handler you can do something like this:
import logging
import logging.handlers
smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.example.com", 25),
fromaddr="someone#something.com",
toaddrs="receiver#mail.com",
subject=u"ERROR IN YOURAPP!")
logger = logging.getLogger()
logger.addHandler(smtp_handler)
try:
raise Exception
except Exception as e:
logger.exception('Unhandled Exception')
for more info see doc

Socket Exception couldn't reconnect to the network in python

when the network goes offline, the sockets throws error instead of reconnecting. It is reconnecting but not trying to achieve the connection. throws error in second or third attempt. Do I need to increase the wait time or is there anything which can be added to make sure the reconnect takes place
import socket,time
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ip = '192.168.xx.x'
port = 4196
address = (ip,port)
client.connect(address)
print("connecting")
while 1:
try:
client.send(b'\x01\x04xxxxxxx')
print("sent")
data = client.recv(1024)
print(data)
time.sleep(5)
except socket.error:
while 1:
print("error")
client.close()
time.sleep(30)
print("reconnecting")
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
while 1:
client.connect(address)
print("connected back")
break
break
OutPut:
connecting
sent
01 04 xxxxxxxxx
error
reconnecting
Error:
Traceback (most recent call last):
File "C:\Users\User\eclipse-workspace\Data\pwr\TCP.py", line 15, in <module>
client.send(b'\x01\x04\xxxxxxxxxxx')
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\User\eclipse-workspace\Data\pwr\TCP.py", line 28, in <module>
client.connect(address)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

how to handle socket errors as exceptions in python + paramiko?

I want to return an error code when the following error gets raised:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 202, in create_group
ssh.connect(hostname, username=user, password=remotepass)
File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 290, in connect
sock.connect(addr)
File "<string>", line 1, in connect
socket.error: [Errno 113] No route to host
>>>
But I'm currently having trouble catching the error raised.
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=user, password=remotepass)
except paramiko.AuthenticationException:
return 259
except socket.error:
return 261
chan = ssh.get_transport().open_session()
chan.exec_command(command)
codest = chan.recv_exit_status()
ssh.close()
return codest
Resulting on this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 207, in create_group
except socket.error:
NameError: global name 'socket' is not defined
>>>
Any ideas?
Do
import socket
in the module where you do the exception handling.
To prevent this problem in the future, run pyflakes on all your source files. That will catch a lot of other errors as well.

Categories