How to check if a network port is open on linux?

前端 未结 12 1033
半阙折子戏
半阙折子戏 2020-12-07 11:07

How can I know if a certain port is open/closed on linux ubuntu, not a remote system, using python? How can I list these open ports in python?

  • Netstat: Is th
12条回答
  •  时光说笑
    2020-12-07 11:15

    In case when you probing TCP ports with intention to listen on it, it’s better to actually call listen. The approach with tring to connect don’t 'see' client ports of established connections, because nobody listen on its. But these ports cannot be used to listen on its.

    import socket
    
    
    def check_port(port, rais=True):
        """ True -- it's possible to listen on this port for TCP/IPv4 or TCP/IPv6
        connections. False -- otherwise.
        """
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.bind(('127.0.0.1', port))
            sock.listen(5)
            sock.close()
            sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            sock.bind(('::1', port))
            sock.listen(5)
            sock.close()
        except socket.error as e:
            return False
            if rais:
                raise RuntimeError(
                    "The server is already running on port {0}".format(port))
        return True
    

提交回复
热议问题