Client Connections
On the client side, the next step is to connect with a
server at a particular port and host. To do this, the client uses
the connect call. connect requires the socket filehandle as
its first argument. The second argument is a data structure
containing the port and hostname that together specify the address.
The Socket package provides the sockaddr_in function to create this
structure for Internet addresses and the sockaddr_un function for Unix domain
addresses.
The sockaddr_in function
takes a port number for its first argument and a 32-bit IP address
for the second argument. The 32-bit address is formed from the
inet_aton function found in the
Socket package. This function takes either a hostname (e.g.,
www.oreilly.com) or a
dotted-decimal string (e.g., 207.54.2.25) and returns the
corresponding 32-bit structure.
Continuing with the previous example, a call to connect could look like this:
my $dest = sockaddr_in (80, inet_aton('www.oreilly.com'));
connect (SH, $dest) || die $!;This call attempts to establish a network connection to the
specified server and port. If successful, it returns true.
Otherwise, it returns false and dies with the error in $!.
Assuming that the connect
call has completed successfully and a connection has been
established, there are a number of functions we can use to write to
and read from the filehandle. For example, the send function sends data to a
socket:
$data = "Hello"; send (FH, $data);
The print function allows a wider variety of ...
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.
Read now
Unlock full access