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>
17 #include <arpa/inet.h>
28 /* client's own static version of several nmh subroutines */
29 static char **client_brkstring (char *, char *, char *);
30 static int client_brkany (char, char *);
31 static char **client_copyip (char **, char **, int);
32 static char *client_getcpy (char *);
33 static void client_freelist(char **);
37 client (char *args, char *service, char *response, int len_response, int debug)
40 char **ap, *arguments[MAXARGS];
41 struct addrinfo hints, *res, *ai;
44 if (args != NULL && *args != 0) {
45 ap = client_copyip (client_brkstring (client_getcpy (args), " ", "\n"),
48 if (servers != NULL && *servers != 0)
49 ap = client_copyip (client_brkstring (client_getcpy (servers), " ", "\n"),
52 if (ap == arguments) {
53 *ap++ = client_getcpy ("localhost");
57 memset(&hints, 0, sizeof(hints));
59 hints.ai_flags = AI_ADDRCONFIG;
61 hints.ai_family = PF_UNSPEC;
62 hints.ai_socktype = SOCK_STREAM;
64 for (ap = arguments; *ap; ap++) {
67 fprintf(stderr, "Trying to connect to \"%s\" ...\n", *ap);
70 rc = getaddrinfo(*ap, service, &hints, &res);
74 fprintf(stderr, "Lookup of \"%s\" failed: %s\n", *ap,
80 for (ai = res; ai != NULL; ai = ai->ai_next) {
82 char address[NI_MAXHOST];
84 rc = getnameinfo(ai->ai_addr, ai->ai_addrlen, address,
85 sizeof(address), NULL, 0, NI_NUMERICHOST);
87 fprintf(stderr, "Connecting to %s...\n",
88 rc ? "unknown" : address);
91 sd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
95 fprintf(stderr, "socket() failed: %s\n", strerror(errno));
99 if (connect(sd, ai->ai_addr, ai->ai_addrlen) == 0) {
106 fprintf(stderr, "Connection failed: %s\n", strerror(errno));
116 strncpy (response, "no servers available", len_response);
122 * Free a list of strings
126 client_freelist(char **list)
128 while (*list++ != NULL)
134 * static copies of three nmh subroutines
137 static char *broken[MAXARGS + 1];
140 client_brkstring (char *strg, char *brksep, char *brkterm)
143 register char c, *sp;
147 for (bi = 0; bi < MAXARGS; bi++) {
148 while (client_brkany (c = *sp, brksep))
150 if (!c || client_brkany (c, brkterm)) {
157 while ((c = *++sp) && !client_brkany (c, brksep) && !client_brkany (c, brkterm))
167 * returns 1 if chr in strg, 0 otherwise
170 client_brkany (char chr, char *strg)
175 for (sp = strg; *sp; sp++)
183 * copy a string array and return pointer to end
186 client_copyip (char **p, char **q, int len_q)
188 while (*p && --len_q > 0)
198 client_getcpy (char *str)
203 len = strlen(str) + 1;
204 cp = mh_xmalloc(len);
206 memcpy (cp, str, len);