7.6.Â Helper Functions

FreeBSD C library contains many helper functions for sockets
programming. For example, in our sample client we hard coded
the time.nist.govIP address. But we do not always know the
IP address. Even if we do, our software is
more flexible if it allows the user to enter the
IP address, or even the domain name.

7.6.1.Â gethostbyname

While there is no way to pass the domain name directly to
any of the sockets functions, the FreeBSD C library comes with
the gethostbyname(3) and gethostbyname2(3)
functions, declared in netdb.h.

Both return a pointer to the hostent
structure, with much information about the domain. For our
purposes, the h_addr_list[0] field of the
structure points at h_length bytes of the
correct address, already stored in the network byte
order.

This allows us to create a much more flexible—and
much more useful—version of our
daytime program:

We now can type a domain name (or an IP
address, it works both ways) on the command line, and the
program will try to connect to its
daytime server. Otherwise, it will still
default to time.nist.gov. However,
even in this case we will use
gethostbyname rather than hard coding
192.43.244.18.
That way, even if its IP address changes in
the future, we will still find it.

Since it takes virtually no time to get the time from your
local server, you could run daytime
twice in a row: First to get the time from time.nist.gov, the second
time from your own system. You can then compare the results
and see how exact your system clock is:

You usually do know the port. But if you are developing a
new protocol, you may be testing it on an unofficial port.
Some day, you will register the protocol and its port (if
nowhere else, at least in your
/etc/services, which is where
getservbyname looks). Instead of
returning an error in the above code, you just use the
temporary port number. Once you have listed the protocol in
/etc/services, your software will find
its port without you having to rewrite the code.