Cannot send and receive udp message in same program - python

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

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").

Related

Capture Loopback Traffic with Python

How to capture loop back traffic in Python, with Wireshark i am able to observe the communication as below:
I want to be the "Man In the middle" in this scenario. As i am trying to make the simulator of a Trace32 debugger in my system.
Edit 10-Aug-2020:
I have tried below code, and receiving error, it seems we can not reuse the same port:
OSError: [WinError 10048] Only one usage of each socket address
(protocol/network address/port) is normally permitted
import socket
UDP_IP = "127.0.0.1"
DEBUG_PORT = 20000
MASTERPORT = 53180
MESSAGE = b"TRACE32 C"
mastersock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
debugsock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
debugsock.bind((UDP_IP, DEBUG_PORT))
while True:
data, addr = debugsock.recvfrom(1024) # buffer size is 1024 bytes
print("Listen on Debugger port: %s" % data)
if (data):
print ("Send back response to Master")
mastersock.sendto(MESSAGE, (UDP_IP, MASTERPORT))

Is there a way to send two messages with socket

Im trying to send a messages from the server to the client
I tried deleting the .close and puting a while loop on print but it still doesn't won't to work
Client
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
while True:
print (s.recv(1024))
Server
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print ('Got connection from', addr)
x = str(input("ënter a message"))
data = x.encode()
c.send(data)
I expect the output to be 2 messages from the server but it is only sending 1 and then closing the connection
Switch your accept and while True: lines. Once you accept a connection, keep sending on the same connection.
Note that TCP is a streaming protocol. There is no concept of "messages", but just a bunch of bytes. If you send fast enough, such as:
c.send(b'abc')
c.send(b'def')
then recv(1024) could receive b'abcdef'. For more complex communication, you'll have to define a protocol and buffer recv until you are sure you have a complete message. A simple way in this case is read until you find a newline, or send a byte (or more) indicating the size of the total message before sending the actual message.

Establishing UDP communication with python

So, I have this code here. This sender script give's me the output properly.
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 0
MESSAGE = "Hi, can you listen to this?"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
I tried to use this script on another host and try to establish a communication between the two. (Both the systems are on the same network ex. 00.000.00.xxx , only the xxx part varies)
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 0
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
Here is the output
Traceback (most recent call last):
File "C:/Users/bshivaku/Desktop/SEnd_Udp_packets.py", line 9, in <module>
sock.bind((UDP_IP, UDP_PORT))
File "C:\Python27\Lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context
I used the ip address of the receiver on the sender script and sender ip address on receiver
I am sure I made a mistake with the UDP_PORT so i used PORT= 0 and tried. How to request for port number? How do I establish the connection? If not the port, where am I going wrong?
When sending a message use a specific port, for example UDP_PORT=8765, otherwise if UDP_PORT is set to 0 then the system will chose a random port for you.
Use the ip address of the receiver host in the sender script and bind to any interface on the receiver script.
On the receiving side use the same UDP port number configured in the sender script.
receiver:
import socket
UDP_IP = "0.0.0.0"
UDP_PORT = 8543
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
sender:
import socket
UDP_IP = "<ip_address_of_receiver>"
UDP_PORT = 8543
MESSAGE = "Hi, can you listen to this?"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
Aside the UDP addresses setting there are not any problems on python side.
About the error:
[Errno 10049] The requested address is not valid in its context
This normally stems from an attempt to bind to an address that is not valid for the local computer: so it seems that the loopback address 127.0.0.1 it is not configured on your machine.
Investigate on the sys admin side, for example check if the IPv4 network stack is enabled on your machine.

Python UDP socket resend data if no data recieved

I want to send some data to a sensor and if the python script doesn't receive the data I want the receive function to timeout and resend the data.
def subscribe():
UDP_IP = "192.168.1.166"
UDP_PORT = 10000
MESSAGE = '6864001e636caccf2393730420202020202004739323cfac202020202020'.decode('hex')
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
recieve_data = recieve()
if recieve_data == subscribe_recieve_on or recieve_data == subscribe_recieve_off:
logging.info('Subscribition to light successful')
else:
logging.info('Subscribition to light unsuccessful')
def recieve():
UDP_IP = "192.168.1.118"
UDP_PORT = 10000
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024)
return data.encode('hex')
subscribe()
At the moment it gets stuck in the receive function if it doesn't receive any data:
data, addr = sock.recvfrom(1024)
However I want it to timeout after e.g. 2 seconds and rerun the subscribe() function.
I've tried using a while true statement with a timeout and try/exception however I get a port currently in use even when closing the port. Also feel this way is messy.
Any ideas would be appreciated.
You get the "currently in use" exception because you are recreating the sockets every time you call either of those functions, without closing them first.
Try creating the sockets beforehand. The response might come before the receiving socket is created in which case the packet is just going to be rejected.
Then you should try only the sendto-recvfrom calls in a loop.
Also you either need to set a timeout with settimeout on the receiving socket so it does not get blocked then catch the timeout exception or use a polling mechanism like select or poll to check whether you have received any data.

Python sockets: sending and receving three multi messages at the same time

I'm working on a project to send some data from the server to the client, like name, age, and country as a messages to the client from the server.
I created this code using python and socket lib but I want to know are there any better ways to get the messages in the same order?
For example I'm sending a "first message" then "second message" then "third message" so the output should be in the same order: "first message" then "second message" then "third message"
Here is my code:
sending
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
MESSAGE2 = "Hello, world2"
MESSAGE3 = "Hello, world3"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))
sock.sendto(MESSAGE2.encode(), (UDP_IP, UDP_PORT))
sock.sendto(MESSAGE3.encode(), (UDP_IP, UDP_PORT))
receiving
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:2", data
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:3", data
instead of using udp use tcp which will make sure that the messages will be in order

Categories

Resources