Tim Brigham
Tim Brigham

Reputation: 574

Why am I getting an empty string from calls to IO::Socket::INET->peerhost?

I'm writing a small script to monitor if certain ports are attempted to be accessed on my Linux box (Centos 6) using Perl 5.10.1. I'm getting back blank entries for my peerhost request. I'm not sure why. It sounds like it may be a failure in the IO socket module (http://snowhare.com/utilities/perldoc2tree/example/IO/Socket.html) but I'm not really sure. Any insight would be much appreciated.

EDIT:

Since I enabled the strict and warnings I'm getting an 'uninitialized value $display' in the cases where I thought it was blank.

#! /usr/bin/perl
use strict;
use warnings;

use IO::Socket;
use Sys::Syslog qw( :DEFAULT setlogsock);
use threads;

my @threads=();
my @ports=(88,110,389);

main(\@ports);

sub main
{
    my $ports=shift;
    setlogsock('unix');
    openlog($0,'','user');
    for my $port (@{$ports} ) {
        push @threads, threads->create(\&create_monitor, $port );
    }
    $_->join foreach @threads;
    closelog;
# wait for all threads to finish
}


sub create_monitor{
    my $LocalPort=shift;

    my $sock = new IO::Socket::INET (
        LocalPort => $LocalPort,
        Proto => 'tcp',
        Listen => 1,
        Reuse => 1,
        ) or die "Could not create socket: $!\n";


    while(1)
    {
        my $peer_connection= $sock->accept;
        my $display = $peer_connection->peerhost();
        my $message="Connection attempt on port $LocalPort from $display";
        #syslog('info', $message);
        print $message."\n";
    }

}

NOTE - it is intentional that this script never finish. I'll eventually wrap this with an init script and have it run as a service.

Upvotes: 4

Views: 1107

Answers (1)

Dirk Stöcker
Dirk Stöcker

Reputation: 1638

Perl accept() has an error code like most other functions. For accept() it is a false return, see also here.

So when you get undefined as result there is an error in accept() call. The error of accept is saved in the errno variable ($!).

Same is true for peerhost() (see here). It also can fail and return an error code.

If you only use the above code without anything else, then probably you reach connection limit of your system (you should close the connections) when accept() fails. See rlimit() to find out how that number can be increased.

One case where peerhost() fails may be that remote connection was closed already.

Upvotes: 1

Related Questions