Marcello has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I use IO::Socket to create a server which accepts connections:
my $sock = new IO::Socket::INET( LocalPort => 8123, Proto => "tcp", Listen => SOMAXCONN, Reuse => 1 );
Since we do not have a firewall installed and I want to limit the number of connections per IP address to 1, is there a solution to block connections from the same IP once connected?

I just keep track of IP numbers now and close the connection when an IP address is already being served, but I would like to refuse the connection instead of accepting and closing it.

Any ideas?

TIA Marcello

Replies are listed 'Best First'.
Re: Block IP addresses with IO::Socket
by Corion (Patriarch) on Oct 23, 2003 at 09:34 UTC

    I think such blocking must be done on a lower TCP level, as Perl shields us from the ugly state machine that is a TCP connection - my way would be to set up a (simplicistic) firewall and manipulate the rules to block packets from within the program:

    1. First connection comes in
    2. Program changes the IP tables to block all further SYN packets from the remote IP to the local server port:
      `ipmasq -A ipblock -i eth0 -o localhost --dest-port 8000 --remote-ip 192.168.1.100`
    3. Second connection comes in and gets blocked by the firewall

    You should still do the second check in your program, and you should maybe clean/expire the firewall blocks from time to time.

    In the end I think that a firewall will be necessary anyway, as you have a machine connected to the internet.

    perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
Re: Block IP addresses with IO::Socket
by Abigail-II (Bishop) on Oct 23, 2003 at 09:52 UTC
    No, user space Perl programs cannot do that. Your only option is to accept or not accept a connection - and you cannot get the information of an incoming connection (like its IP address) without first accepting it.

    What you want to do is normally done at kernel level (although in some implementations, the kernel can consult a user space program to make the decision).

    Abigail