3 * client.c -- connect to a server
7 * This code is Copyright (c) 2002, by the authors of nmh. See the
8 * COPYRIGHT file in the root directory of the nmh distribution for
9 * complete copyright information.
16 #include <sys/socket.h>
17 #include <netinet/in.h>
20 #ifdef HAVE_ARPA_INET_H
21 # include <arpa/inet.h>
33 /* client's own static version of several nmh subroutines */
34 static char **client_brkstring (char *, char *, char *);
35 static int client_brkany (char, char *);
36 static char **client_copyip (char **, char **, int);
37 static char *client_getcpy (char *);
38 static void client_freelist(char **);
42 client (char *args, char *service, char *response, int len_response, int debug)
45 char **ap, *arguments[MAXARGS];
46 struct addrinfo hints, *res, *ai;
49 if (args != NULL && *args != 0) {
50 ap = client_copyip (client_brkstring (client_getcpy (args), " ", "\n"),
53 if (servers != NULL && *servers != 0)
54 ap = client_copyip (client_brkstring (client_getcpy (servers), " ", "\n"),
57 if (ap == arguments) {
58 *ap++ = client_getcpy ("localhost");
62 memset(&hints, 0, sizeof(hints));
64 hints.ai_flags = AI_ADDRCONFIG;
66 hints.ai_family = PF_UNSPEC;
67 hints.ai_socktype = SOCK_STREAM;
69 for (ap = arguments; *ap; ap++) {
72 fprintf(stderr, "Trying to connect to \"%s\" ...\n", *ap);
75 rc = getaddrinfo(*ap, service, &hints, &res);
79 fprintf(stderr, "Lookup of \"%s\" failed: %s\n", *ap,
85 for (ai = res; ai != NULL; ai = ai->ai_next) {
87 char address[NI_MAXHOST];
89 rc = getnameinfo(ai->ai_addr, ai->ai_addrlen, address,
90 sizeof(address), NULL, 0, NI_NUMERICHOST);
92 fprintf(stderr, "Connecting to %s...\n",
93 rc ? "unknown" : address);
96 sd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
100 fprintf(stderr, "socket() failed: %s\n", strerror(errno));
104 if (connect(sd, ai->ai_addr, ai->ai_addrlen) == 0) {
111 fprintf(stderr, "Connection failed: %s\n", strerror(errno));
121 strncpy (response, "no servers available", len_response);
127 * Free a list of strings
131 client_freelist(char **list)
133 while (*list++ != NULL)
139 * static copies of three nmh subroutines
142 static char *broken[MAXARGS + 1];
145 client_brkstring (char *strg, char *brksep, char *brkterm)
148 register char c, *sp;
152 for (bi = 0; bi < MAXARGS; bi++) {
153 while (client_brkany (c = *sp, brksep))
155 if (!c || client_brkany (c, brkterm)) {
162 while ((c = *++sp) && !client_brkany (c, brksep) && !client_brkany (c, brkterm))
172 * returns 1 if chr in strg, 0 otherwise
175 client_brkany (char chr, char *strg)
180 for (sp = strg; *sp; sp++)
188 * copy a string array and return pointer to end
191 client_copyip (char **p, char **q, int len_q)
193 while (*p && --len_q > 0)
203 client_getcpy (char *str)
208 len = strlen(str) + 1;
209 cp = mh_xmalloc(len);
211 memcpy (cp, str, len);