A Basic Port Scanner in Python, Java

One of the first tools you need for a penetration test is a Port Scanner. There are some very awesome port scanners out there like Nmap but did you ever wonder how to make one? Here's how: 


#! /usr/bin/env python
# PortScanner.py
# Author: Abdul Fatir
# E-Mail: abdulfatirs@gmail.com

from socket import *
HostName = raw_input("Host Name: ")
try:
	# gethostbyname(HostName) returns the IPv4 address of a website
	IPaddress = gethostbyname(HostName)
except:
	print "[-] Could not find host."
	quit()
portstring = raw_input("Ports (separated by commas):")
ports = portstring.split(",")
print "\n[*] Scan results for "+HostName+" ("+IPaddress+"):"
# setdefaulttimeout(1) sets the waiting time for website response to 1 seconds. This may result in closed port even though the port may be open if it takes more than 1 second.
setdefaulttimeout(1)
for port in ports:
	try:
		connection = socket(AF_INET,SOCK_STREAM)
		# socket.connect((IP,PORT)) connect to the IP at given port.
		connection.connect((IPaddress,int(port)))
		connection.send('hello\r\n')
		# socket.recv(BUFFER_SIZE) receives the server response
		data = connection.recv(8)
		# If we have reached this far that means the port is open.
		print "\t[+] "+port+"/tcp open"
	except:
		print "\t[-] "+port+"/tcp closed"
	finally:
		connection.close()

Download the python code from pastebin

Here is a similar example in Java:


import java.net.*;
import java.util.*;
import java.io.*;
import static java.lang.System.out;
public class PortScanner
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        out.print("HostName: ");
        String host=br.readLine();
        InetAddress address=null;
        try
        {
            address = InetAddress.getByName(host);
        }
        catch(UnknownHostException uhe)
        {
            out.print("[-] Could not find host.");
            System.exit(0);
        }
        out.print("Ports (separated by commas): ");
        String portstring = br.readLine();
        StringTokenizer ports = new StringTokenizer(portstring,",");
        out.println("[*] Scan results for "+host+" ("+address.getHostAddress()+"):");
        while(ports.hasMoreTokens())
        {
            int port = 0;
            try{
                port = Integer.parseInt(ports.nextToken());
                Socket conn=new Socket();
                conn.connect(new InetSocketAddress(host,port),1000);
                conn.close();
                out.println("\t[+] "+port+"/tcp open");
            }
            catch(SocketTimeoutException ste)
            {
                out.println("\t[-] "+port+"/tcp closed");
            }
        }
        
    }
}

Download the Java code from pastebin

Note: This is a very basic example and must not be used as a substitute for tools like Nmap.