Ad

OSError: [Errno 22] Invalid Argument Socket Python Socket

- 1 answer

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.

Ad

Answer

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():
...
Ad
source: stackoverflow.com
Ad