Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

808 Communicating with a Network Printer Chapter 21


34 if (err || (optind != argc - 1))
35 err_quit("usage: print [-t] filename");
36 if ((fd = open(argv[optind], O_RDONLY)) < 0)
37 err_sys("print: can’t open %s", argv[optind]);
38 if (fstat(fd, &sbuf) < 0)
39 err_sys("print: can’t stat %s", argv[optind]);
40 if (!S_ISREG(sbuf.st_mode))
41 err_quit("print: %s must be a regular file", argv[optind]);

42 /*
43 * Get the hostname of the host acting as the print server.
44 */
45 if ((host = get_printserver()) == NULL)
46 err_quit("print: no print server defined");
47 if ((err = getaddrlist(host, "print", &ailist)) != 0)
48 err_quit("print: getaddrinfo error: %s", gai_strerror(err));
49 for (aip = ailist; aip != NULL; aip = aip->ai_next) {
50 if ((sfd = connect_retry(AF_INET, SOCK_STREAM, 0,
51 aip->ai_addr, aip->ai_addrlen)) < 0) {
52 err =errno;

[34 – 41] When getopt completes processing the command options, it leaves the
variableoptindset to the index of the first nonoptional argument. If this is
any value other than the index of the last argument, then the wrong number of
arguments was specified (we support only one nonoptional argument). Our
error processing includes checks to ensurethat we can open the file to be
printed and that it is a regular file (as opposed to a directory or other type of
file).
[42 – 48] We get the name of the host wherethe printer spooling daemon is running by
calling theget_printserverfunction fromutil.c.Then we translate the
host name into a network address by calling getaddrlist (also from
util.c).
Note that we specify the service as ‘‘print.’’Aspart of installing the printer
spooling daemon on a system, we need to make surethat/etc/services(or
the equivalent database) has an entry for the printer service. When we select a
port number for the daemon, it would be a good idea to select one that is
privileged, to prevent malicious users from writing applications that pretend
to be a printer spooling daemon but instead steal copies of the files we try to
print. This means that the port number should be less than 1,024 (recall
Section 16.3.4) and that our daemon will have to run with superuser privileges
to allow it to bind to a reserved port.
[49 – 52] We try to connect to the daemon using one address at a time from the list
returned bygetaddrinfo.Wewill try to send the file to the daemon using
the first address to which we can connect.
Free download pdf