User Tools

Site Tools


perl:forking_server
# Tyler Bletsch
use IO::Socket;
 
# Will listen on $listenPort
my $sockListen = new IO::Socket::INET (LocalPort => $listenPort, Proto => 'tcp', Listen => 1000, Reuse => 1);
die "Could not create socket: $!\n" unless $sockListen;
 
print "Listening on port $listenPort.\n";
 
while (1) {
	print "Waiting to accept on port $listenPort...\n";
	$sockClient = $sockListen->accept(); # Get next client
	$clientSockAddr = $sockClient->peername();
	($clientPort, $clientAddr) = sockaddr_in($clientSockAddr);
	$clientHost = gethostbyaddr($clientAddr, AF_INET);
	$clientIP = inet_ntoa($clientAddr);
	if (!$clientHost) {
		print "Connected to $clientIP, local port $clientPort!\n";
	} elsif ($clientHost eq $clientIP) {
		print "Connected to $clientHost, local port $clientPort!\n";
	} else {
		print "Connected to $clientHost ($clientIP), local port $clientPort!\n";
	}
 
	my $pid = fork();
	die "Cannot fork '$!'" unless defined $pid;
	if ($pid) { # Parent
		close $sockClient;
		next;
	}
 
	# Child
 
	### DO STUFF WITH $sockClient
	#print $sockClient scalar localtime; # Uncomment to make this a simple time server
 
	close $sockClient;
	exit;
}
perl/forking_server.txt · Last modified: 2009/08/13 09:56 by tkbletsc

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki