soger
soger

Reputation: 1237

Perl Modification of a read-only value attempted for hash

I have a server that also counts the number of distinct IPs connected in a minute. I get a "Modification of a read-only value attempted" in the marked line in the code below:

$lsock=new IO::Socket::INET(LocalPort=>$port,Proto=>'tcp',Listen=>1,Reuse=>1);
$clients={};
while (1) {
    $sock=$lsock->accept();
    if ($sock) {
        $clients->{$sock->peerhost()}=1; # THIS LINE !!!
        ...
    }
}

# then later from an alarm signal I do:
sub save_stats {
    my $cnt=scalar keys %$clients;
    $clients={};
    ...
}

The error appears very rarely, once a month or less, but it's driving me insane, can someone please explain it to me why and what can I do?

Upvotes: 2

Views: 291

Answers (1)

soger
soger

Reputation: 1237

After a lot of investigation I found the answer. It can happen that the connection is lost between accept() and peerhost(). In this case the peeerhost() function's return value is not suitable as a hash key. The solution is very simple, if peerhost() returns a "false" ignore the connection alltogether.

Upvotes: 1

Related Questions