3 * client.c -- connect to a server
5 * This code is Copyright (c) 2002, by the authors of nmh. See the
6 * COPYRIGHT file in the root directory of the nmh distribution for
7 * complete copyright information.
14 #include <sys/socket.h>
15 #include <netinet/in.h>
18 #ifdef HAVE_ARPA_INET_H
19 # include <arpa/inet.h>
31 /* client's own static version of several nmh subroutines */
32 static char **client_brkstring (char *, char *, char *);
33 static int client_brkany (char, char *);
34 static char **client_copyip (char **, char **, int);
35 static char *client_getcpy (char *);
36 static void client_freelist(char **);
40 client (char *args, char *service, char *response, int len_response, int debug)
43 char **ap, *arguments[MAXARGS];
44 struct addrinfo hints, *res, *ai;
47 if (args != NULL && *args != 0) {
48 ap = client_copyip (client_brkstring (client_getcpy (args), " ", "\n"),
51 if (ap == arguments) {
52 *ap++ = client_getcpy ("localhost");
56 memset(&hints, 0, sizeof(hints));
58 hints.ai_flags = AI_ADDRCONFIG;
60 hints.ai_family = PF_UNSPEC;
61 hints.ai_socktype = SOCK_STREAM;
63 for (ap = arguments; *ap; ap++) {
66 fprintf(stderr, "Trying to connect to \"%s\" ...\n", *ap);
69 rc = getaddrinfo(*ap, service, &hints, &res);
73 fprintf(stderr, "Lookup of \"%s\" failed: %s\n", *ap,
79 for (ai = res; ai != NULL; ai = ai->ai_next) {
81 char address[NI_MAXHOST];
83 rc = getnameinfo(ai->ai_addr, ai->ai_addrlen, address,
84 sizeof(address), NULL, 0, NI_NUMERICHOST);
86 fprintf(stderr, "Connecting to %s...\n",
87 rc ? "unknown" : address);
90 sd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
94 fprintf(stderr, "socket() failed: %s\n", strerror(errno));
98 if (connect(sd, ai->ai_addr, ai->ai_addrlen) == 0) {
105 fprintf(stderr, "Connection failed: %s\n", strerror(errno));
115 strncpy (response, "no servers available", len_response);
121 * Free a list of strings
125 client_freelist(char **list)
127 while (*list++ != NULL)
133 * static copies of three nmh subroutines
136 static char *broken[MAXARGS + 1];
139 client_brkstring (char *strg, char *brksep, char *brkterm)
142 register char c, *sp;
146 for (bi = 0; bi < MAXARGS; bi++) {
147 while (client_brkany (c = *sp, brksep))
149 if (!c || client_brkany (c, brkterm)) {
156 while ((c = *++sp) && !client_brkany (c, brksep) && !client_brkany (c, brkterm))
166 * returns 1 if chr in strg, 0 otherwise
169 client_brkany (char chr, char *strg)
174 for (sp = strg; *sp; sp++)
182 * copy a string array and return pointer to end
185 client_copyip (char **p, char **q, int len_q)
187 while (*p && --len_q > 0)
197 client_getcpy (char *str)
202 len = strlen(str) + 1;
203 cp = mh_xmalloc(len);
205 memcpy (cp, str, len);