Python socket accept invalid argument

OSError: [Errno 22] Недопустимый аргумент в сокете python3 [закрыто]

У меня проблема с программированием сокетов в Python 3. Я получаю исключение, которое не приводит к сбою программы, а просто отображается в терминале.

from PyQt4 import QtCore, QtGui from imigui import Ui_MainWindow class imiserv(QtGui.QMainWindow): send_msg = pyqtSignal('QString', 'QString') def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.Sport_lineEdit.setMaxLength(5) self.ui.Sconnect_pushButton.clicked.connect(self.serv) self.send_msg.connect(self.write_msg) def write_msg(self, lbl_msg= None, txt_msg= None): if lbl_msg: self.ui.C_label.setText(lbl_msg) if txt_msg: self.ui.Clog_textEdit.setText(txt_msg) def serv(self): MY_LOCK = threading.Lock() class CountT(threading.Thread): def __init__(self, parent): threading.Thread.__init__(self) self._parent= parent def run(self): MY_LOCK.acquire() self._parent.send_msg.emit("Waiting connections","") while True: cliconn, (addr, remoport)= self._parent.clis.accept() clirecmsg= str(cliconn.recv(1024) self._parent.send_msg.emit(": is connected.".format(addr, remoport), ":".format(addr, remoport) cliconn.close() MY_LOCK.release() try: self.clis= socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.clis.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) clierhost= str(self.ui.Sip_lineEdit.text()) clierport= int(self.ui.Sport_lineEdit.text()) self.clis.bind((clierhost, clierport)) self.clis.listen(5) a= CountT(self) a.daemon= True a.start() except socket.error as err: err= str(err) print(err) 

И вот ошибки, которые произошли в перекрестном порядке (эта ошибка отображается только в ОС Linux):

Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python3.3/threading.py", line 637, in _bootstrap_inner self.run() File "imiclilap.py", line 34, in run cliconn, (addr, remoport)= self._parent.clis.accept() File "/usr/lib/python3.3/socket.py", line 135, in accept fd, addr = self._accept() OSError: [Errno 22] Invalid argument Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python3.3/threading.py", line 637, in _bootstrap_inner self.run() File "imiclilap.py", line 34, in run cliconn, (addr, remoport)= self._parent.clis.accept() File "/usr/lib/python3.3/socket.py", line 135, in accept fd, addr = self._accept() OSError: [Errno 22] Invalid argument 

Источник

Читайте также:  Html text drop shadows

OSError: [WinError 10022] An invalid argument was supplied | Python Socket Error

I was working on socket programming. The code was running fine on Python 2 but it was throwing an error while running on Python 3 version.

Error is as follows:

>>py server.py Traceback (most recent call last): File "server.py", line 20, in c, cAddr = s.accept() File "C:\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 212, in accept fd, addr = self._accept() OSError: [WinError 10022] An invalid argument was supplied

This is the exception thrown by the Operating System while executing socket program on Windows OS.

Solution:

It is mandatory to add listen()

  • “s” is the socket object.
  • 2o is the maximum number of queued connections. You can set any number as per your requirement.

I had missed this line to add in my socket program. Because of this, my program was crashing.

After adding this line of code just before the s.accept() , my issue is solved.

How to debug WinError in Socket Programming?

It is not easy to debug any socket programming errors.

WinError 10022 is for not passing valid arguments to the socket. This is just one example. There are many socket errors you will come across. Each error code has different meaning. You can check the error codes and their meanings on Official Microsoft website.

To avoid this crash, it is always good practice to add exception handling in any socket program you write.

If you are getting any error in your socket program and not able to fix it, write in the comment. I will help you on my best.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid argument exception during socket.accept on AF_INET6 #164

Invalid argument exception during socket.accept on AF_INET6 #164

Comments

If I remove the setsockopt call on line 192, the testcase works as expected.

Is this a bug, or am I not creating an IPv6 socket correctly?

The text was updated successfully, but these errors were encountered:

Right, there are two issues here: (1) what we should be doing with IPV6_V6ONLY by default (which overlaps with #72), and (2) fixing the exception.

Am I reading your table correctly as saying that the problem happens when you set up a listen socket with IPV6_V6ONLY set to False, then accept a v4 connection, and then trio tries to set IPV6_V6ONLY on the new labeled-as-ipv6-but-secretly-actually-a-v4-socket? That makes a lot of sense :-). So at the very least we should tolerate an error here.

As to the larger question of defaults, there are a few competing considerations:

The problem with accepting the system default is that it leads to non-portable programs (in particular in this case: test on linux, everything works fine because in fact everyone leaves bindv6only set to 0, and then you’re broken on windows because they make IPV6_V6ONLY default to enabled. And in practice, setting V6ONLY=False doesn’t actually make programs magically handle ipv4 and ipv6 equally, because e.g. people expect that their web server’s connection logs will contain ipv4 addresses rather than ipv6-mapped-ipv4 addresses. So I figured better to have consistency and then let people pick if they want something different. libuv does something similar, though IIRC they have the opposite default from trio’s current setting. I don’t have a strong opinion on which default is better 🙂

But then there’s another issue: initially I hoped that trio.socket would be the standard user-level API for doing networking in trio, but in the course of implementing SSL support have come around to the conclusion that we need a higher-level layer that provides a dedicated «stream» abstraction. There’s a huge work-in-progress branch in #107 with the initial part of this. As part of this, I’ve defined a SocketStream class that adapts a socket into the Stream interface; and probably I will also add high-level helpers for connecting to a host+port and for listening on a port, that are defined at this level. So. if trio.socket is becoming the «low-level raw» networking API, maybe it does make more sense to remove the default-setting code from here, and instead handle it in the higher-level layer. (So in particular, the «listen on this port» interface would automatically create both ipv4 and and ipv6 sockets, and transparently listen on both of them.)

Источник

OSError: [Errno 22] Invalid argument python socket connection problem

Currently am creating TCP socket to send and receive data for a backend app but am facing self.socket.connect((«localhost», 8000)) OSError: [Errno 22] Invalid argument error. have looked up similar errors on here along with other forums and has something to do with me placing self.socket.connect((«localhost», 8000)) within the other indented code in the start_client function but when I try to place it elsewhere within the file I’m either getting self is not defined or invalid argument for socket_connect Here’s my ClientServer.py code:

import socket from threading import Thread MAX_BUFFER_SIZE = 4096 class ClientServer(Thread): def __init__(self): print("Client Server started w/ new threads. ") Thread.__init__(self) self.socket = None def send_to_Server(self, data): print('Time to send data to Server. %s', data) self.socket.send(data.encode("utf8")) def receive_from_Server(self): print('Time to receive from Server. ') result_bytes = self.socket.recv(MAX_BUFFER_SIZE) result_string = result_bytes.decode("utf8") print("Result from server is <>".format(result_string)) def start_client(self): # Creates TCP socket self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Re-uses socket self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Binds socket to host and port self.socket.bind(("localhost", 8000)) # Connects socket to host and port self.socket.connect(("localhost", 8000)) print('Client connected. ') threads = [] def connect_client(self): while True: # Become a server socket self.socket.listen(5) self.__clients = <> # Starts connection (clientSocket, client_address) = self.socket.accept() newthread = ClientServer("localhost", 8000) newthread.start threads.append(newthread) for t in threads: t.join() cs = ClientServer() cs.start_client() cs.connect_client() cs.send_to_Server('Hello') cs.receive_from_Server() 

Источник

Python setsockopt invalid argument with IP_ADD_MEMBERSHIP

I am trying to create socket that can receive multicast UDP packages on my Ubuntu using Python 2.7.3. I have based my code on https://stackoverflow.com/a/1794373/1444854 Unfortunately I keep getting the same error:

 self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 22] Invalid argument 
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(("", 12345)) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 

Where for ‘mreq’ I have tried various stuff, of which I show a few here. For the format in the struct examples I have used both with and without the network byte order indicator (‘!’). The native one seems to double the size (from 8 to 16). I have also tried both signed and unsigned longs (‘l’ and ‘L’).

group = "127.0.0.1" # Or any other ipv4 address. mreq = socket.inet_aton(group) + socket.inet_aton("0.0.0.0") mreq = struct.pack("4sL", socket.inet_aton(self.group), socket.inet_aton("0.0.0.0")) mreq = struct.pack("4sL", socket.inet_aton(self.group), socket.htonl(socket.INADDR_ANY)) mreq = struct.pack("4sL", socket.inet_aton(self.group), socket.INADDR_ANY) 

At this point I do not know what the problem is, and could use some help with this. I thought that the wrong ‘mreq´ would provide an issue, but after so many tries I feel there must be something else I am missing. Any help is appreciated. If more information is needed, I will gladly provide it. EDIT: The problem, which I totally overlooked, was the fact that I needed a proper multicast interface. Using ‘ifconfig wlan0’ or any other interface, you can check that MultiCast is in fact enabled. Furthermore I think any address between 224.3.* and 224.250.* has not been assigned for other uses. The ‘mreq’ that works for me is

 mreq = struct.pack("!4sl", socket.inet_aton(self.group), socket.INADDR_ANY) 

Источник

Оцените статью