in reply to Close Socket Force client to quit.

I simplified some real code I have, and made it into this demo.

One thing you may notice is that, after fork, as the best practice, in the child process, I close the parent socket; and in the parent process, I close the child socket. The purpose of this is to release resouces, as you don't want to hold anything you don't need.

As jasonk pointed out, you can use peerhost() to get the peer ip addr in xx.xx.xx.xx (ascii) format. His way is very straight forward. Just for the sack of completeness, I provide a different way, by using inet_ntoa($client->peeraddr()). The peeraddr() function returns the peer ip in number format, inet_ntoa is then called to convert number format into ascii format.

server.pl use IO::Socket; use strict; $| ++; my $server = new IO::Socket::INET(Timeout => 7200, Proto => "tcp", LocalPort => 3000, Reuse => 1, Listen => 2); my $num_of_client = -1; while (1) { my $client; do { $client = $server->accept; } until (defined($client)); print "new clinet accepted, id = ", ++ $num_of_client, ", peeraddr = ", inet_ntoa($client->peeraddr()), ", peerport = ", $client->peerport(), "\n"; if (!fork) { close($server);#this only closes the copy in the child process while (1) { my $msg; $client->recv($msg, 1000); if ($msg eq "") { die "child $num_of_client is inactive\n"; } else { print "rcvd $msg from client ", $num_of_client, "\n"; sleep(2); print $client $msg; } } } else { close($client); #this only closes the copy in the parent proce +ss, assume the parent no longer need talk to the client } } client.pl: use IO::Socket; use strict; my $server = new IO::Socket::INET(Proto => "tcp", PeerAddr => "localhost", PeerPort => 3000, Reuse => 1, Timeout => 7200) || die "failed to connect to server\n"; while (1) { print $server "abcd"; my $msg; $server->recv($msg, 1000); if ($msg eq "") { die "server is not responding"; } else { print "recv'd ", $msg, "\n"; } }