Getting Network Information
Perl supports network programming in a way that is very familiar to those who have written network code in C programs. In fact, most of the Perl functions that provide network access have the same names and similar parameters as their C counterparts. We can’t teach a complete course on network programming in this chapter, but let’s take a look at one of the task fragments to see how it’s done in Perl.
One of the things you need to find out is the network address that
goes with a network name, or vice versa. In C, you use the
gethostbyname
routine to convert a network name to a network address. You then use
this address to create a connection from your program to another
program somewhere else.
The Perl function to translate a host name to an address has the same name and similar parameters as the C routine, and looks like this:
($name, $aliases, $addrtype, $length, @addrs) = gethostbyname($name); # generic form of gethostbyname
The parameter to this function is a hostname—for example, slate.bedrock.com. The return value is a list of four or more parameters, depending on how many addresses are associated with the name. If the hostname is not valid, the function returns an empty list.
If gethostbyname is called in a scalar context,
only the (first) address is returned.
When gethostbyname()completes successfully,
$name is the
canonical
name, which differs from the input name if the input name
is an alias. $aliases is a list of space-separated names by which ...
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