Saturday 4 August 2012

Making a simple port scanner

Lets make a simple port scanner with opens a full TCP connection to detect if a port is open or not.
This is not the best way to scan because it makes a lot of noise, some other ways are Half TCP (TCP SYN) and TCP FIN.
Code in python::

import socket
i = “127.0.0.1″
for p in range(19, 26):
spy = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
spy.connect((i, p)

)
print p,” Open”
except :
print p,”closed”
It searches 127.0.0.1 from port 19 to 25. The data is hard coded but sys.argv[] can be used to take arguments from command line.. Python is indent sensitive and here I can’t find any [code] tag so if you copy paste the above code it will give errors the indentation should be corrected to work properly.
Code in Perl::

use IO::Socket;
$port = 19;
while ($port < 26){
$spy = new IO::Socket::INET (PeerAddr => '127.0.0.1',
PeerPort => $port,
Proto => 'tcp');
if ($spy){
close $spy;
print "$port -open\n";
$port = $port + 1;
}
else{
print "$port -closed\n";
$port = $port + 1;
}
}

Code in Ruby::


require 'socket'
require 'timeout'
ports = 19..26
ports.each do |spy|
begin
Timeout::timeout(10){TCPSocket.new("127.0.0.1", spy)}
rescue
puts "closed : #{spy}"
else
puts "open : #{spy}"
end
end
Code in Java::

import java.net.*;
import java.io.IOException;
public class javaps {
public static void main(String[] args)
{
String remote = "172.16.0.1";
for (int port = 19; port <= 26; port++) {
try {
Socket s = new Socket(remote, port);
System.out.println("The port " + port + " of " + remote + " is open");
s.close();
}
catch (IOException ex) {
System.out.println("The port " + port + " of " + remote + " is closed");
}}}}
These are just one way of coding port scanners :)

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...