Sobes.tech
Junior

How to check if a port is open on a remote or local host?

sobes.tech AI

Answer from AI

To check an open port on a remote or local host, you can use the following methods:

  1. netcat (nc): A versatile tool for working with network connections.

    • Local host:
      nc -zv localhost <port>
      
    • Remote host:
      nc -zv <remote_host> <port>
      

    The options -z (zero-I/O mode) and -v (verbose) are used for scanning without sending data and for detailed output.

  2. telnet: A protocol for remote management, which can be used to check connection on a specified port.

    • Local host:
      telnet localhost <port>
      
    • Remote host:
      telnet <remote_host> <port>
      

    If the connection is established (usually a prompt or empty line appears), the port is open. You can close it by pressing Ctrl+], then quit and Enter.

  3. nmap: A powerful port scanner. Requires installation.

    • Local host:
      nmap -p <port> localhost
      
    • Remote host:
      nmap -p <port> <remote_host>
      

    The output will show the port status: open, closed, or filtered.

  4. < /dev/tcp or < /dev/udp (in Bash): In Bash, you can use file descriptors to create TCP or UDP connections.

    • Local host (TCP):
      timeout 1 bash -c "cat < /dev/tcp/localhost/<port>" 2>/dev/null && echo "Port <port> is open" || echo "Port <port> is closed"
      
    • Remote host (TCP):
      timeout 1 bash -c "cat < /dev/tcp/<remote_host>/<port>" 2>/dev/null && echo "Port <port> is open" || echo "Port <port> is closed"
      

    timeout is used to prevent hanging if the port is closed. 2>/dev/null hides error output. This method does not work for UDP.

  5. Python: Using sockets for checking.

    import socket
    
    def check_port(host, port):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)  # Set timeout
        try:
            s.connect((host, port))
            print(f"Port {port} on {host} is open")
        except (socket.timeout, ConnectionRefusedError):
            print(f"Port {port} on {host} is closed or filtered")
        finally:
            s.close()
    
    # Example usage
    check_port("localhost", 80)       # Check local host
    check_port("google.com", 443)  # Check remote host
    

The choice of method depends on available tools, operating system, and the specific task. netcat and nmap are among the most flexible and informative tools.