# Port Scanning

When either defending or attacking a system, it is important to learn as much as you can about it. One way to do this is with port scanning. There are up to 65,535 ports which could be in use on a system. Understanding what these ports are and how they are used is critical from both a defensive and offensive perspective.

This post covers some common/useful commands for port scanning.

## LSOF

lsof provides a list of all open files belonging to all active processes.

lsof -i :<port>
Lists all processes listening on a specific port. Includes process id, making it pretty easy to kill if you need to.

## NETSTAT

From a host, you can list out all network connections on a system.

### Commands

netstat -a
Lists all connections

netstat -at
Lists all TCP connections

netstat -au
Lists all UDP connections

netstat -tl
Lists all listening TCP connections

netstat -ant
Disables DNS reverse lookup for faster output

netstat -antp
Includes process/PID in output

## NETCAT

Netcat is the self professed “swiss army knife” of TCP/IP (see it’s man page). It can create almost any kind of TCP or UDP connection you could need, making it a fantastic debugging/exploration tool.

### Commands

nc <host> <port>
The simplest usage creates a TCP connection to a given host and target port. Any standard input you then type will be sent to the host. Below you can see me establishing a TCP connection on port 80 of a Metasploitable VM and then sending a GET request to that port and receiving the apache server’s response.

Similarly, you can run this command with the verbose flag (-v) to get more information on the port.

nc -lvp <port>
From a host you can also listen (verbosely) on a port. You will then be able listen to and send traffic on that port (as shown below, I sent myself a message with netcat on the port I was listening on with netcat).

## NMAP

Probably the best known and most powerful port scanner. For a great reference guide best to go to the source.

### Commands

nmap -sS <host(s)> -oA <filename>
TCP SYN Scan.

Additonally, you can scan for a specific port.

nmap -sU <host(s)> -oA <filename>
UDP SYN Scan. Note that this scan takes longer than TCP. You can hit the up arrow while it’s running to check on it’s status. Just take time remaining at face value.

nmap -sV <host(s)> -oA <filename>
Version Scan. Rather than just scanning to see if ports are open, version scan pulls banners and other information after establishing a TCP session to make a best guess on the version of the service running on the open port.