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>
25 /* client's own static version of several nmh subroutines */
26 static char **client_brkstring (char *, char *, char *);
27 static int client_brkany (char, char *);
28 static char **client_copyip (char **, char **, int);
29 static char *client_getcpy (char *);
30 static void client_freelist(char **);
34 client (char *args, char *service, char *response, int len_response, int debug)
37 char **ap, *arguments[MAXARGS];
38 struct addrinfo hints, *res, *ai;
41 if (args != NULL && *args != 0) {
42 ap = client_copyip (client_brkstring (client_getcpy (args), " ", "\n"),
45 if (servers != NULL && *servers != 0)
46 ap = client_copyip (client_brkstring (client_getcpy (servers), " ", "\n"),
49 if (ap == arguments) {
50 *ap++ = client_getcpy ("localhost");
54 memset(&hints, 0, sizeof(hints));
56 hints.ai_flags = AI_ADDRCONFIG;
58 hints.ai_family = PF_UNSPEC;
59 hints.ai_socktype = SOCK_STREAM;
61 for (ap = arguments; *ap; ap++) {
64 fprintf(stderr, "Trying to connect to \"%s\" ...\n", *ap);
67 rc = getaddrinfo(*ap, service, &hints, &res);
71 fprintf(stderr, "Lookup of \"%s\" failed: %s\n", *ap,
77 for (ai = res; ai != NULL; ai = ai->ai_next) {
79 char address[NI_MAXHOST];
81 rc = getnameinfo(ai->ai_addr, ai->ai_addrlen, address,
82 sizeof(address), NULL, 0, NI_NUMERICHOST);
84 fprintf(stderr, "Connecting to %s...\n",
85 rc ? "unknown" : address);
88 sd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
92 fprintf(stderr, "socket() failed: %s\n", strerror(errno));
96 if (connect(sd, ai->ai_addr, ai->ai_addrlen) == 0) {
103 fprintf(stderr, "Connection failed: %s\n", strerror(errno));
113 strncpy (response, "no servers available", len_response);
119 * Free a list of strings
123 client_freelist(char **list)
125 while (*list++ != NULL)
131 * static copies of three nmh subroutines
134 static char *broken[MAXARGS + 1];
137 client_brkstring (char *strg, char *brksep, char *brkterm)
140 register char c, *sp;
144 for (bi = 0; bi < MAXARGS; bi++) {
145 while (client_brkany (c = *sp, brksep))
147 if (!c || client_brkany (c, brkterm)) {
154 while ((c = *++sp) && !client_brkany (c, brksep) && !client_brkany (c, brkterm))
164 * returns 1 if chr in strg, 0 otherwise
167 client_brkany (char chr, char *strg)
172 for (sp = strg; *sp; sp++)
180 * copy a string array and return pointer to end
183 client_copyip (char **p, char **q, int len_q)
185 while (*p && --len_q > 0)
195 client_getcpy (char *str)
200 len = strlen(str) + 1;
201 cp = mh_xmalloc(len);
203 memcpy (cp, str, len);