简体   繁体   中英

How to properly close an asyncio connection where local_addr is used

I am making a TCP connection using asyncio and then closing it some time later. I need to specify local_addr as there are a number of interfaces available on the host machine.

import asyncio

async def main():
    print("Connecting...")
    try:
        reader, writer = await asyncio.open_connection('169.254.6.123', 55555, local_addr=('169.254.6.11', 15333))
    except Exception as e:
        print(e)
        return
        
    await asyncio.sleep(3)
    writer.close()
    ret = await writer.wait_closed()
    print(ret)
    
    
asyncio.run(main())

This works fine on first run but then on second run I get an error back:

[WinError 52] You were not connected because a duplicate name exists on the network.

If I do NOT have the local_addr set then it works fine (I have to disable all my other network interfaces to ensure it gets routed otherwise it times out as the 'network location cannot be reached' - can't find a route).

Am I doing something wrong in closing the connection when local_addr is set?

It works on retry with local_addr set if I wait some time before trying to run again (I guess some cache is cleared??).

Not sure if this is only an issue on Windows (using Windows 10)

I was re-using the port...so OS was giving the error.

Set local_addr port to 0 and the OS will choose the port. See this answer .

reader, writer = await asyncio.open_connection('169.254.6.123', 55555, local_addr=('169.254.6.11', 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM