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";
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.