2 * client.c -- connect to a server
4 * This code is Copyright (c) 2002, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
13 #include <sys/socket.h>
14 #include <netinet/in.h>
17 #ifdef HAVE_ARPA_INET_H
18 # include <arpa/inet.h>
30 /* client's own static version of several nmh subroutines */
31 static char **client_brkstring (char *, char *, char *);
32 static int client_brkany (char, char *);
33 static char **client_copyip (char **, char **, int);
34 static char *client_getcpy (char *);
35 static void client_freelist(char **);
39 client (char *args, char *service, char *response, int len_response, int debug)
42 char **ap, *arguments[MAXARGS];
43 struct addrinfo hints, *res, *ai;
46 if (args != NULL && *args != 0) {
47 ap = client_copyip (client_brkstring (client_getcpy (args), " ", "\n"),
50 if (ap == arguments) {
51 *ap++ = client_getcpy ("localhost");
55 memset(&hints, 0, sizeof(hints));
57 hints.ai_flags = AI_ADDRCONFIG;
59 hints.ai_family = PF_UNSPEC;
60 hints.ai_socktype = SOCK_STREAM;
62 for (ap = arguments; *ap; ap++) {
65 fprintf(stderr, "Trying to connect to \"%s\" ...\n", *ap);
68 rc = getaddrinfo(*ap, service, &hints, &res);
72 fprintf(stderr, "Lookup of \"%s\" failed: %s\n", *ap,
78 for (ai = res; ai != NULL; ai = ai->ai_next) {
80 char address[NI_MAXHOST];
82 rc = getnameinfo(ai->ai_addr, ai->ai_addrlen, address,
83 sizeof(address), NULL, 0, NI_NUMERICHOST);
85 fprintf(stderr, "Connecting to %s...\n",
86 rc ? "unknown" : address);
89 sd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
93 fprintf(stderr, "socket() failed: %s\n", strerror(errno));
97 if (connect(sd, ai->ai_addr, ai->ai_addrlen) == 0) {
104 fprintf(stderr, "Connection failed: %s\n", strerror(errno));
114 strncpy (response, "no servers available", len_response);
120 * Free a list of strings
124 client_freelist(char **list)
126 while (*list++ != NULL)
132 * static copies of three nmh subroutines
135 static char *broken[MAXARGS + 1];
138 client_brkstring (char *strg, char *brksep, char *brkterm)
141 register char c, *sp;
145 for (bi = 0; bi < MAXARGS; bi++) {
146 while (client_brkany (c = *sp, brksep))
148 if (!c || client_brkany (c, brkterm)) {
155 while ((c = *++sp) && !client_brkany (c, brksep) && !client_brkany (c, brkterm))
165 * returns 1 if chr in strg, 0 otherwise
168 client_brkany (char chr, char *strg)
173 for (sp = strg; *sp; sp++)
181 * copy a string array and return pointer to end
184 client_copyip (char **p, char **q, int len_q)
186 while (*p && --len_q > 0)
196 client_getcpy (char *str)
201 len = strlen(str) + 1;
202 cp = mh_xmalloc(len);
204 memcpy (cp, str, len);