Ed Prince
Ed Prince

Reputation: 714

Python: How to convert the address recieved from a recvfrom() function to a string?

Summary

I am adding a feature to a python udp listener that send back an acknowledgement to the device it's receiving from. In my case, at the moment that device is localhost, but in the future will be an MT4000 telemetry device.

The problem

I am using the recvfrom() function to receive the data and source address from the device sending data. The return value is a pair (string, address) where string is a string representing the data received and address is the address of the socket sending the data. This question us focusing on the address. The address is returning

('127.0.0.1', 57121)

I understand this means the source I.P is 127.0.0.1 ie localhost, and the 57121 represents the port that the data has been sent through. My goal is to split this data up in order to send back an acknowledgement.

My Solution

The code I have receiving the data is this: (s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) data, addr = s.recvfrom(1024)

So far I have tried this method of splitting up the data:

sourceIp = addr[3:-9]

I was under the impression that this should split up the string as such:

sourceIp = 127.0.0.1

It does however only output this: ()

My thinking at the moment is that this is not actually a string, and so that method of splitting up does not work. Is there another way of splitting, or method of converting? Thanks.

Upvotes: 1

Views: 12282

Answers (1)

Vincas Dargis
Vincas Dargis

Reputation: 555

('127.0.0.1', 57121) is a tuple, immutable container with two items.

To get ip/port do it like this:

data, addr = s.recvfrom(1024)
ip = addr[0]
port = addr[1]

Or you can unpack it like you did with data, addr = ...:

data, addr = s.recvfrom(1024)
ip, port = addr

Or, even shorted approach:

data, (ip, port) = s.recvfrom(1024)

Upvotes: 10

Related Questions