get open TCP port in Python

后端 未结 5 1284
走了就别回头了
走了就别回头了 2020-12-14 01:24

I want to get any random open TCP port on localhost in Python. What is the easiest way?

5条回答
  •  有刺的猬
    2020-12-14 01:54

    The ephemeral ports basically lie in range 49152 - 65535. if you want to check ports in bigger range then just change the values in randint.

    import pustil
    from random import randint
    def getfreeport():
        port = randint(49152,65535)
        portsinuse=[]
        while True:
            conns = pstuil.net_connections()
            for conn in conns:
                portsinuse.append(con.laddr[1])
            if port in portsinuse:
                port = randint(49152,65535)
            else:
                break
        return port
    

提交回复
热议问题