Sockets
Beginning |
Previous |
Next
Primer On Sockets
Take a look at http://www.world.std.com/~jimf
for a quick primer on sockets.
A Server Example
Here is an untested socket server that listens to a
port, accepts connections and echos back what was sent:
#!d:/usr/local/perl/bin/perl -w
require 5.002;
use Socket;
($port) = @ARGV;
$port = 2345 unless $port;
$sockaddr = 'S n a4 x8';
($name, $aliases, $proto) = getprotobyname('tcp');
($name, $aliases, $port) = getservbyname($port, 'tcp')
unless $port =~ /^\d+$/;
$this = pack($sockaddr, AF_INET, $port, "\0\0\0\0");
select(NS); $| = 1; select(stdout); # Do non-buffered I/O
socket(S, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
bind(S, $this) || die "bind: $!";
listen(S, 5) || die "connect: $!";
select(S); $| = 1; select(stdout);
while (1)
{
print "Listening again\n";
($addr = accept(NS,S)) || die $!;
print "accept ok\n";
($af,$port,$inetaddr) = unpack($sockaddr,$addr);
@inetaddr = unpack('C4',$inetaddr);
print "$af $port @inetaddr\n";
while ()
{
print;
print NS;
}
}
A Client Example
Here is an untested socket client that connects to a
server and sends what you type at the keyboard to the socket:
#!d:/usr/local/perl/bin/perl -w
require 5.002;
use Socket;
($them,$port) = @ARGV;
$port = 2345 unless $port;
$them = 'localhost' unless $them;
$SIG{'INT'} = 'dokill';
$sockaddr = 'S n a4 x8';
chop($hostname = `hostname`);
($name, $aliases, $proto) = getprotobyname('tcp');
($name, $aliases, $port) = getservbyname($port, 'tcp')
unless $port =~ /^\d+$/;
($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
$this = pack($sockaddr, AF_INET, 0, $thisaddr);
$that = pack($sockaddr, AF_INET, $port, $thataddr);
socket(S, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
bind(S, $this) || die "bind: $!";
connect(S, $that) || die "connect: $!";
select(S); $| = 1; select(STDOUT);
if ($child = fork)
{
while (<>)
{
print S;
}
sleep 3;
&dokill;
}
else
{
while ()
{
print;
}
}
sub dokill
{
kill 9,$child if $child;
}
Beginning |
Previous |
Next
Last Modified: $Date: 1997/05/09 07:32:02 $