use DBI;
use strict;
use IO::Socket;
# initialize host and port
my $host = shift || $ARGV[0];
my $port = shift || $ARGV[1];
my $proto = getprotobyname('tcp');
my $iaddr = inet_aton($host);
my $paddr = sockaddr_in($port, $iaddr);
my $time = localtime(time);
for(;;){

my $sock = new IO::Socket::INET(PeerAddr => $host, PeerPort => $port,Proto => "tcp",)
or die "Cannot connect to PBX at address: $host port: $port: $!";

while (<$sock>) {
s/^\0+//; # Remove leading null characters
print $_;
chomp ($_);
#$_ =~ s/^[^ ]+//;
if ($_ =~m"/") {
&DBconnect; #send data to the database subroutine
}
} #Close While loop

sub DBconnect {
# MySQL Connection parameters
my $dbuser= "root";
my $dbpassword= "voyage";
my $dbhost= "localhost";
my ($line, $mon, $day, $stime, $pm, $hrs, $mins, $sec, $callp, $leaddigit, $callno, $speed, $callp2, $transf, $acccode, $sysid, $tester);

			$mon = substr ($_, 1,2);
			$day = substr ($_, 4,2);
			$stime = substr($_, 7,5);
			$pm = substr($_, 12,1);
			$hrs = substr($_, 14,2);
			$mins = substr($_, 17,2);
			$sec = substr($_, 20,2);
			$callp = substr($_, 23,4);
			$leaddigit = substr($_, 29,3);
			$callno = substr($_, 33,26);
			$speed = substr($_, 60,1);
			$callp2 = substr($_, 61,4);
			$transf = substr($_, 67,4);
			$acccode = substr($_, 72,12);
			$sysid = substr($_, 85,3);
if ($acccode == ""){$acccode = 0}
# Establish the connection which returns a DB handle
my $dbh= DBI->connect("dbi:mysql:database=smdr;host=$dbhost",$dbuser,$dbpassword) or die $DBI::errstr;
# Prepare the SQL statement
my $sth= $dbh->prepare("INSERT INTO import VALUE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)") or die $DBI::errstr;
# Send the statement to the server
$sth->execute($mon,$day,$stime,$pm,$hrs,$mins,$sec,$callp,$leaddigit,$callno,$speed,$callp2,$transf,$acccode,$sysid,$tester);
# Close the database connection
$dbh->disconnect or die $DBI::errstr;
} #Close DBconnect subroutine

#close the socket
close $sock or die "close: $!";
print "socket closed";
print "<br />";
}
