Showing posts with label socket. Show all posts
Showing posts with label socket. Show all posts

Tuesday, November 2, 2010

Python - Writing a traceroute using sockets

I recently learned, how to write a traceroute using socket programming in python. I am sharing it below. I don't take any credit for the code. I may have picked bits and pieces from various different resources on the Internet, as a part of my learning process. It's not very elegant but demonstrates the purpose. Perhaps, some day I can improve it and add few enhancements to it.

#!/usr/bin/python
import sys
import socket

def traceroute(dest_name):
    dest_addr = socket.gethostbyname(dest_name)
    port = 33434
    max_hops = 30
    print dest_name
    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')
    ttl = 1
    while True:
        print ttl,
        recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        recv_socket.bind(("", port))
        send_socket.sendto("", (dest_name, port))
        curr_addr = None
        curr_name = None
        try:
            _, curr_addr = recv_socket.recvfrom(512)
            curr_addr = curr_addr[0]

            try:
                curr_name = socket.gethostbyaddr(curr_addr)[0]
            except socket.error:
                curr_name = curr_addr
        except socket.error:
            pass
        finally:
            send_socket.close()
            recv_socket.close()

        if curr_addr is not None:
            curr_host = "%s (%s)" % (curr_name, curr_addr)
        else:
            curr_host = "*"
        print "%d\t%s" % (ttl, curr_host)

        ttl += 1
        if curr_addr == dest_addr or ttl > max_hops:
            break

if __name__ == "__main__":
    traceroute(sys.argv[1])


Can be executed as -

>sudo ./traceroute.py xharpreetx.com

Sunday, July 25, 2010

Perl - How to create a tcp socket?

The following program can be used to create a tcp connection to a host on a specified port.
The program attempts connection at a periodic interval, which is passed as 'execution_interval'.

#!/usr/bin/perl
use IO::Socket;
use POSIX qw/strftime/;
if (@ARGV != 4)
{
  usage(); 
  exit;              
}
my $hostname = $ARGV[0];
my $port = $ARGV[1];
my $timeout = $ARGV[2];
my $interval = $ARGV[3];

my $logdir = "/tmp/";
my $datestamp = strftime('%m-%d-%y_%H:%M:%S',localtime);
$mday = (localtime(time))[3];

my $logfile = $logdir."$hostname\_$port\_tcp_socket\_$datestamp.log";
open LOG, ">>","$logfile" or die $!;
LOG->autoflush(1);
while(1) {
    my $sock = new IO::Socket::INET (PeerAddr => $hostname,
                                     PeerPort => $port,
                                     Proto => 'tcp',
                                     Timeout => $timeout);
    $cur_datestamp = strftime('%m-%d-%y_%H:%M:%S',localtime);
    $cur_mday = (localtime(time))[3];   
    if(!$sock) {
        print LOG "\n$cur_datestamp : Error - Could not create socket to $hostname on $port: $!";
        sleep $interval;
        next;       
    }   
    if($cur_mday != $mday) {
        close(LOG);
        $logfile = $logdir."$hostname\_$port\_tcp_socket\_$datestamp.log";
        open LOG, ">>","$logfile" or die $!;
        LOG->autoflush(1);
        $mday = $cur_mday;
    }   
   
    print LOG "\n$cur_datestamp : Socket created to $hostname on $port";   
    close($sock);
    sleep $interval;
}

close(LOG);

sub usage
{
  print "Invalid parameters \nUsage: ./tcp_socket.pl \n";
}



Please let me know, of any corrections/improvements.