user2563949
user2563949

Reputation: 161

Cannot send and receive udp message in same program

I am able to send and receive UDP messages in separate programs, but I'm not able to do the same task in one program.

import socket

UDP_IP = "192.168.1.178"
UDP_PORT = 8888
msg = 'test'

print "UDP target IP: ", UDP_IP
print "UDP target PORT: ", UDP_PORT
print "Message: ", msg

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(msg, (UDP_IP, UDP_PORT))


UDP_IP2 = "192.168.1.198"

sock.bind((UDP_IP2, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print "received message:", data

With this program, I am able to send UDP messages, however, I am not able to receive any messages from the other machine.

What am I doing wrong?

Thanks in advance,
Mikkel

Upvotes: 1

Views: 773

Answers (1)

Andrew Svetlov
Andrew Svetlov

Reputation: 17386

In your example you try to bind socket addr after sending, what's wrong. Address can be bound to socket only before any data transfer.

If there is no explicit bind OS sets any free (unused) port number in range [1024, 65535] on first .send()/.recv() call.

Next, socket can be bound only to single IP (except special case '0.0.0.0' which means "all host's interfaces").

Upvotes: 1

Related Questions