Finding out all processes associated with open sockets

Normally I’ve only used the 'netstat' command to find out what are the sockets opened in the operating system by using '-a' flag, but the new thing I’ve discovered recently is that netstat even allows me to track the processes that are opening them, via the '-p' flag. A simple dump of the command on my system gives the following output:

# netstat -ap       
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name   
tcp        0      0 *:http                  *:*                     LISTEN      6695/apache2        
tcp        0      0 *:ssh                   *:*                     LISTEN      6604/sshd           
udp        0      0 *:bootpc                *:*                                 5294/dhcpcd         
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node PID/Program name    Path
unix  2      [ ACC ]     STREAM     LISTENING     10287  6696/apache2        /var/run/cgisock
unix  2      [ ACC ]     STREAM     LISTENING     9767   6324/gdm            /tmp/.gdm_socket

... remaining output truncated.

The '-p' flag allows us to track applications that are holding onto open sockets, which is a good way to understand why certain sockets may have to be open, like bootpc in my example, which is necessary for the DHCP daemon to function.

Knowing this information will allow you to close down any unnecessary services that you do not need, reducing the amount of attack vectors that your machine is exposed to.