Skip to Main Content
Perl in a Nutshell, 2nd Edition
book

Perl in a Nutshell, 2nd Edition

by Nathan Patwardhan, Ellen Siever, Stephen Spainhour
June 2002
Beginner content levelBeginner
759 pages
80h 42m
English
O'Reilly Media, Inc.
Content preview from Perl in a Nutshell, 2nd Edition

Server Connections

After creating a socket with the socket function as you did previously, a server application must go through the following steps to receive network connections:

  1. Bind a port number and machine address to the socket

  2. Listen for incoming connections from clients on the port

  3. Accept a client request and assign the connection to a specific filehandle

We start out by creating a socket for the server:

my $proto = getprotobyname('tcp');
socket(FH, PF_INET, SOCK_STREAM, $proto) || die $!;

The filehandle $FH is the generic filehandle for the socket. This filehandle only receives requests from clients; each specific connection is passed to a different filehandle by accept, where the rest of the communication occurs.

A server-side socket must be bound to a port on the local machine by passing a port and an address data structure to the bind function via sockaddr_in. The Socket module provides identifiers for common local addresses, such as localhost and the broadcast address. Here we use INADDR_ANY, which allows the system to pick the appropriate address for the machine:

my $sin = sockaddr_in (80, INADDR_ANY);
bind (FH, $sin) || die $!;

The listen function tells the operating system that the server is ready to accept incoming network connections on the port. The first argument is the socket filehandle. The second argument gives a queue length, in case multiple clients are connecting to the port at the same time. This number indicates how many clients can wait for an accept at one time. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl by Example, Fourth Edition

Perl by Example, Fourth Edition

Ellie Quigley
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington
Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 0596002416Errata Page