Testing if a server port is actually open


There are actually a whole lot of possibilities to do that, the most simple one probably to use a simple telnet:

telnet example.net 80

Or the good old nmap:

nmap -sS -O -p80 example.net

 

In a Bash script you can simple do it this way:

#!/bin/bash
test=$(nc -z -v -w1 example.net 80 2>&1)
if [[ $test == Connection*succeeded* ]]; then
    # put your code here
fi

 

A simple Ruby script could look like this:

#!/usr/bin/ruby

require 'socket'
require 'timeout'

def port_open?(ip, port)
begin
   Timeout.timeout(2) do
      begin
         TCPSocket.new(ip, port)
      rescue Errno::ENETUNREACH
         retry
      end
   end
rescue Timeout::Error
 # do nothing
end
end

if port_open?("example.net", 80)
 # put your code here
end

 

And in PHP:

<?php
$fp = fsockopen("example.net", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)
\n";
} else {
    // put your code here
    fclose($fp);
}

 

Or what about Python:

#!/usr/bin/python
import socket;
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('example.net',80))
if result == 0:
   print "Port is open"
else:
   print "Port is not open"

 

How about Perl:

#!/usr/bin/perl

use IO::Socket;

$socket = IO::Socket::INET->new(PeerAddr => "example.net" , PeerPort => 80 , Proto => 'tcp' , Timeout => 1);

if( $socket )
{
    print "Port is open.\n";
}
else
{
    print "Port is closed\n";
}

 

Eventually Java:

import java.net.*;

public class CheckPort
{
       public static void main(String args[])
       {
                 try
                 {
                  Socket sock = new Socket("example.net",80);
                  System.out.println("Port 80 is open");
                  sock.close();
                 }
                 catch (Exception e)
                 {
                     e.printStackTrace();
                 }
        }
}