Python Socket invalid Argument - python

Some util informations:
OS: Windows 10 (with WSL2 installed)
IDE: Emacs
I'm working in a project using the python socket library.
I made a class to organize the server processes, inside that server I have the method "requestConnection", when I call the method it gives me an error "Errno 22 [invalid argument]".
Here's the error:
Traceback (most recent call last):
File "SocketChat.py", line 4, in <module>
servidor.requestConnection()
File "/mnt/c/Users/Mauro/Development/Projects/SocketChat/server.py", line 16, in requestConnection
self.con = self.server_socket.accept()
File "/usr/lib/python3.8/socket.py", line 292, in accept
fd, addr = self._accept()
OSError: [Errno 22] Invalid argument
Here's the main code:
from server import Server, Chat
servidor = Server('127.0.0.1', '5000')
servidor.requestConnection()
chat = Chat(servidor.receiveMsg())
Here's the classes:
import socket
class Server:
def __init__(self, host, port):
self.host = host
self.port = port
self.addr = (host, port)
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def shutDown(self):
self.server_socket.close()
def requestConnection(self):
self.con = self.server_socket.accept()
def receiveMsg(self):
receive = self.con.recv(1024)
return str(receive)
class Chat:
def __init__(msg):
self.msg = msg
pass
def newMsg(self):
print(f"new message: {self.msg.decode()}")
pass
If you know how to solve this problem, please give-me the answer

Try to pass the port number as integer, not string:
from server import Server, Chat
servidor = Server('127.0.0.1', 5000)

Related

OSError: [Errno 22] invalid argument socket python socket

I have some app that use UDP socket. Each app can to send and receive date.
In an app that recevie data, code is below:
receiver app:
UDPSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
bufferSize= 1024
EnginePort=2000
def ReceiveSocket():
global UDPSocket
global AddressPort
global bufferSize
AddressPort = ("127.0.0.2", EnginePort)
# Bind to address and ip
UDPSocket.bind(AddressPort)
print("UDP server up and listening")
bytesAddressPair = UDPSocket.recvfrom(bufferSize)
message = pickle.loads(bytesAddressPair[0])
address = bytesAddressPair[1]
clientMsg = "Message from Client:{}".format(message)
clientIP = "Client IP Address:{}".format(address)
print(clientMsg)
print(clientIP)
while True:
ReceiveSocket()
sending a simple message:
import socket
import pickle
UDP_IP = "127.0.0.2"
UDP_PORT = 2000
MESSAGE = "Hello, World!"
print ("UDP target IP:", UDP_IP)
print ("UDP target port:", UDP_PORT)
print ("message:", MESSAGE)
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
sock.sendto(pickle.dumps(MESSAGE), (UDP_IP, UDP_PORT))
When receive data ,give me this error:
receiver output:
Message from Client:Hello, World!
Client IP Address:('127.0.0.2', 2003)
Traceback (most recent call last):
File "/home/pi/RoomServerTestApps/Engine.py", line 88, in <module>
ReceiveSocket()
File "/home/pi/RoomServerTestApps/Engine.py", line 29, in ReceiveSocket
UDPSocket.bind(AddressPort)
OSError: [Errno 22] Invalid argument
But when the ReceiveSocket() is outside the while true(), app work well.
Please help me about this.
Thanks.
Get bind() out of the loop. You've already bound to the port at first run, that's why the second+ run fails.
AddressPort = ("127.0.0.2", EnginePort)
UDPSocket.bind(AddressPort)
def ReceiveSocket():
...

Client sending a file to server via socket

I wrote a client and a server program in which client sends a file to the server and server prints the contents of the file. This is the code snippet:
Server---------------->serverprog.py
import socket
from threading import *
class Server:
gate = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 0
file = ''
def __init__(self, port):
self.port = port
# self.gate.bind((self.host, self.port))
self.gate.bind(("127.0.0.1", self.port))
self.listen()
def listen(self):
self.gate.listen(10)
while True:
conn,address = self.gate.accept()
self.receiveFilename(conn)
def receiveFileName(self, sock):
buf = sock.recv(1024)
print('First bytes I got: ' + buf)
a = Server(8888)
Client ------------------>clientprog.py
import socket
from threading import *
class Client:
gateway = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#host = socket.gethostname()
host = ''
port = 0
file = ''
def __init__(self, host, port, file):
self.port = port
self.host = host
self.file = file
self.connect()
def connect(self):
self.gateway.connect((self.host, self.port))
self.sendFileName()
self.sendFile()
def sendFileName(self):
self.gateway.send("name:" + self.file)
def sendFile(self):
readByte = open(self.file, "rb")
data = readByte.read()
readByte.close()
self.gateway.send(data)
self.gateway.close()
a = Client('127.0.0.1', 8888, 'datasend.txt')
If i compile both client and server simultaneously, it gives me the following error for server program:
Traceback (most recent call last):
File "receivefilepg.py", line 25, in <module>
a = Server(8888)
File "receivefilepg.py", line 15, in __init__
self.listen()
File "receivefilepg.py", line 20, in listen
self.receiveFilename(conn)
AttributeError: Server instance has no attribute 'receiveFilename'
What am i doing wrong here? Any suggestions would be helpful!
The Error tells you all you need to know, you have a typo in the server.listen method, instead of calling self.receiveFileName you called self.receiveFilename.

Running multiple sockets at the same time in python

I am trying to listen and send data to several sockets at the same time. When I run the program I get en error saying:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 704, in __init__
if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
OSError: [Errno 9] Bad file descriptor
The first socket starts up correctly, but once I try to start a new one I get the error.
class bot:
def __init__(self, host, port):
self.host = host
self.port = port
sock = socket.socket()
s = None
def connect_to_server(self):
self.s = ssl.wrap_socket(self.sock)
self.s.connect((self.host, self.port))
Above is the class and then I'm running several instances.
def run_bots(bots):
for bot in bots:
try:
threading.Thread(target=bot.connect_to_server()).start()
except:
print(bot.host)
print("Error: unable to start thread")
bots = []
b = bot('hostname.com', 1234)
b1 = bot('hostname1.com', 1234)
bots.append(b)
bots.append(b1)
run_bots(bots)
I don't know what to do. Anyone have an idea of what could be the problem?
You are using the same socket. Create one for each bot:
class bot:
def __init__(self, host, port):
self.host = host
self.port = port
self.s = None
def connect_to_server(self):
sock = socket.socket()
self.s = ssl.wrap_socket(sock)
self.s.connect((self.host, self.port))

How to skip a bad host when generating an asyncore.dispatcher object?

import asyncore
class HTTPClient(asyncore.dispatcher):
def __init__(self, host, path):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.connect( (host, 80) )
self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %
(path, host), 'ascii')
def handle_connect(self):
pass
def handle_close(self):
self.close()
def handle_read(self):
print(self.recv(8192))
def writable(self):
return (len(self.buffer) > 0)
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
client = HTTPClient('www.bocaonews.com.br', '/')
asyncore.loop()
And an error was raised:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "***.py", line 15, in __init__
self.connect( (host, 80) )
File "***\lib\asyncore.py", line 339, in connect
err = self.socket.connect_ex(address)
socket.gaierror: [Errno 11004] getaddrinfo failed
The HTTP client is the example of the official documentation. The error was raised because the host www.bocaonews.com.br is not accessible.
So my question is how to modify the code to let a client automatically close the connection when the host is bad? I can examine the host before generating the dispatcher. But it is less efficient.
asyncore doesn't offer much in the way of simplified error handling. Mostly, it leaves you responsible for this. So the solution is to add error handling to your application code:
try:
client = HTTPClient('www.bocaonews.com.br', '/')
except socket.error as e:
print 'Could not contact www.bocaonews.com.br:', e
else:
asyncore.loop()
To make your life a little easier, you may not want to call connect inside HTTPClient.__init__.
Also, for comparison, here's a Twisted-based HTTP/1.1 client:
from twisted.internet import reactor
from twisted.web.client import Agent
a = Agent(reactor)
getting = a.request(b"GET", b"http://www.bocaonews.com.br/")
def got(response):
...
def failed(reason):
print 'Request failed:', reason.getErrorMessage()
getting.addCallbacks(got, failed)
reactor.run()

Sending Txt file to server from client using python sockets

i am trying to create a server/client in python using sockets for sending text and other media files.
Scenario:- Client takes host, port and file name as parameters and send the file to server.
Error Description:- while trying to execute the below client code, having text file "tos" in same directory as client.Getting below error.
**$ python Cli.py 127.0.0.1 5007 tos**
Traceback (most recent call last):
File "Cli.py", line 32, in <module>
client= Client(host,port,file)
File "Cli.py", line 15, in __init__
self.connect(file)
File "Cli.py", line 20, in connect
self.sendFile(file)
File "Cli.py", line 26, in sendFile
readByte = open(file, "rb")
**IOError: [Errno 2] No such file or directory: ''**
Note:- Also please describe if there is anyway to send file to server, searching the hard drive.
Server:-
from socket import *
port = 5007
file = ''
class Server:
gate = socket(AF_INET, SOCK_STREAM)
host = '127.0.0.1'
def __init__(self, port):
self.port = port
self.gate.bind((self.host, self.port))
self.listen()
def listen(self):
self.gate.listen(10)
while True:
print("Listening for connections, on PORT: ", self.port)
add = self.gate.accept()
self.reciveFileName()
self.reciveFile()
def reciveFileName(self):
while True:
data = self.gate.recv(1024)
self.file = data
def reciveFile(self):
createFile = open("new_"+self.file, "wb")
while True:
data = self.gate.recv(1024)
createFile.write(data)
createFile.close()
server= Server(port)
listen()
Client:-
#!/usr/bin/env python
from socket import *
host = ''
port = 5007
file = ''
class Client:
gateway = socket(AF_INET, SOCK_STREAM)
def __init__(self, host,port, file):
self.port = port
self.host = host
self.file = file
self.connect()
def connect(self):
self.gateway.connect((self.host, self.port))
self.sendFileName(file)
self.sendFile(file)
def sendFileName(self):
self.gateway.send("name:" +self.file)
def sendFile(self):
readByte = open(self.file, "rb")
data = readByte.read()
readByte.close()
self.gateway.send(data)
self.gateway.close()
client= Client(host,port,file)
connect()
At the moment file = '' which in not a valid filename. I would also suggest renaming file to filename for clarity.
Had this task as Homework 3 months ago.
The solution for this is pretty simple - You simply need to read the file, put the readed text in a string variable and send it. Look at this server code:
HOST = '192.168.1.100'
PORT = 8012
BUFSIZE = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(SOMAXCONN)
fileOpen = open("D:/fileLocation.txt")
g = f.read()
print 'Waiting For Connection..'
clientsock, addr = serversock.accept()
print 'Connection Established From: ', addr`
clientsock.sendall(g)
This is a very simple way to do so.
The client simply receives the data (as text) and save it in the wanted location.
Worked for me with BMP,PNG and JPG images also.

Categories

Resources