1

I am new in micropython and testing it out, if it can fit the needs for my next project. I have set up a script to test it and there I run three async jobs in an endless loop. one of them is a tiny webserver, which should act as an API. The construct is working fine, I just need to know, how can I get the clients IP address, which is calling my API webservice (it will be only a local IP, so no worries about reverse proxies etc.)? So I would like to have the clients IP in the Method APIHandling, in this snippet just to print it out:

async def APIHandling(reader, writer):
    request_line = await reader.readline()
    # We are not interested in HTTP request headers, skip them
    while await reader.readline() != b"\r\n":
        pass
    request = str(request_line)
    try:
        request = request.split()[1]
    except IndexError:
        pass
    print("API request: " + request + " from IP: ")
    req = request.split('/')
    #do some things here
    response = html % stateis
    writer.write(response)
    await writer.drain()
    await writer.wait_closed()

async def BusReader():
        #doing something here
        await asyncio.sleep(0)

async def UiHandling():
        #doing something else here
        await asyncio.sleep(0.5)

async def Main():
    set_global_exception()
    loop = asyncio.get_event_loop()
    loop.create_task(asyncio.start_server(APIHandling, Networking.GetIPAddress(), 80))
    loop.create_task(UiHandling())
    loop.create_task(BusReader())
    loop.run_forever()

try:
    asyncio.run(Main())
finally:
    asyncio.new_event_loop()

The only thing I found was this: Stream.get_extra_info(v) - but I do not have a Stream avaliable anywhere?

Note: This is just a snippet with the essential parts of my actual script, so you will find references to other classes etc. which are not present in this code example.

kamp
  • 41
  • 4

1 Answers1

3

Nevermind, I was too stupid to see that "writer" is actually a Stream, where I can get the clients IP with writer.get_extra_info('peername')[0]

kamp
  • 41
  • 4