usocket recovering socket information (host, port)

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
caligo
Posts: 1
Joined: Thu Dec 10, 2020 5:43 pm

usocket recovering socket information (host, port)

Post by caligo » Thu Dec 10, 2020 6:02 pm

Hello, folks

Been through the forum, docs and code looking for a solution or at least a hint about this, but wasn't quite successful. How do I get the host, port from a client connection? Dumbest echo application possible:

server

Code: Select all

from usocket import AF_INET, getaddrinfo, inet_ntop, socket, SOCK_STREAM

info = getaddrinfo("127.0.0.1", 65432, 0, SOCK_STREAM)

addr = info[0][-1]
print('Server Addr ', inet_ntop(AF_INET, addr))

s = socket()
s.bind(addr)
s.listen(0)
c, addr = s.accept()
print('Client Addr ', inet_ntop(AF_INET, addr))

while True:
    data = c.recv(1024)
    if not data:
        break
    c.send(data)

c.close()
s.close()
client

Code: Select all

from usocket import AF_INET, getaddrinfo, inet_ntop, socket, SOCK_STREAM


addr = getaddrinfo("127.0.0.1", 65432, 0, SOCK_STREAM)[0][-1]
print('Addr ', addr)

s = socket()
s.connect(addr)
s.send(b'Hello, world')
data = s.recv(1024)

print('Received', repr(data))
s.close()
As you can see server is listening on 127.0.0.1:65432. How do I reverse the bytesarray that getaddrinfo returns me? My hope was that inet_ntop would do the job returning me proto, host, port or something close, but the only thing I get is something that looks like an IP. And I'm assuming that on accept the addr value returned is similar to what getaddrinfo returns. A bytesarray containing that information. If I inspect the bytesarray I can identify the 127.0.0.1 and port should be somewhere in there. But how do reverse it?

Post Reply