Table of Contents

Network - Open Port

About

How to know from a localhost which port are open on a remote host (ie that a firewall is not used or that the process is up and listen)

Definition

TCP

When the scanner sends a SYN packet to open a TCP connection and gets:

UDP

Scanning UDP ports is more difficult because UDP does not use handshakes and programs tend to discard UDP packets that they cannot process. When an UDP packet is sent to a port that has no program bound to it, an ICMP error packet is returned. That port can then be considered closed. When no answer is received, the port can be considered either filtered by a firewall or open. Many people abandoned UDP scanning because simple UDP scanners cannot distinguish between filtered and open ports

List / Test open port

Scanner

nmap -Pn -p T:port hostName
nc -w1 -z --ssl github.com 443
echo $?
0

# 20-30 is the port range
nc -z host.example.com 20-30
Connection to host.example.com 22 port [tcp/ssh] succeeded!
Connection to host.example.com 25 port [tcp/smtp] succeeded!

Ansible

wait for module

- name: Testing that the port is open
   wait_for:
      host: hostName
      port: 1433
      state: started
      timeout: 5

Powershell

Test for open port with powershell:

Test-NetConnection hostname -Port 9999
ComputerName     : hostname
RemoteAddress    : 137.116.198.16
RemotePort       : 9999
InterfaceAlias   : Wi-Fi
SourceAddress    : 192.168.135.148
TcpTestSucceeded : True

function testport {
    param
    (
        [Parameter(Mandatory=$true, HelpMessage='The remote host')]
        [string]$remoteHost,
        [Parameter(Mandatory=$true, HelpMessage='The remote port')]
        [string]$remotePort
    ) 

    $tcpClient = New-Object Net.Sockets.TcpClient
    try
    {
        $tcpClient.Connect($remoteHost,$remotePort) 
    } catch {
        # Just to not see the exception message
    }

    if($tcpClient.Connected)
    {
	    "  * Port $remotePort is operational"
    }
    else
    {
	    "  * Port $remotePort is closed"
    }
    $tcpClient.Close()
    
}

$remoteHost = "hostname"
$port = 80
"Test Remote Host on $remoteHost"
testport $remoteHost $port