]>
diplodocus.org Git - nmh/blob - sbr/client.c
1 /* client.c -- connect to a server
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
11 #include <sys/socket.h>
12 #include <netinet/in.h>
14 #include <arpa/inet.h>
19 client (char *server
, char *service
, char *response
, int len_response
,
23 struct addrinfo hints
, *res
, *ai
;
25 if (!server
|| *server
== '\0') {
26 snprintf(response
, len_response
, "Internal error: NULL server name "
27 "passed to client()");
33 hints
.ai_flags
= AI_ADDRCONFIG
;
35 hints
.ai_family
= PF_UNSPEC
;
36 hints
.ai_socktype
= SOCK_STREAM
;
39 fprintf(stderr
, "Trying to connect to \"%s\" ...\n", server
);
42 rc
= getaddrinfo(server
, service
, &hints
, &res
);
45 snprintf(response
, len_response
, "Lookup of \"%s\" failed: %s",
46 server
, gai_strerror(rc
));
50 for (ai
= res
; ai
!= NULL
; ai
= ai
->ai_next
) {
52 char address
[NI_MAXHOST
];
53 char port
[NI_MAXSERV
];
55 rc
= getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, address
,
56 sizeof(address
), port
, sizeof port
,
57 NI_NUMERICHOST
| NI_NUMERICSERV
);
59 fprintf(stderr
, "Connecting to %s:%s...\n",
60 rc
? "unknown" : address
, rc
? "--" : port
);
63 sd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
67 fprintf(stderr
, "socket() failed: %s\n", strerror(errno
));
72 if (connect(sd
, ai
->ai_addr
, ai
->ai_addrlen
) == 0) {
80 fprintf(stderr
, "Connection failed: %s\n", strerror(errno
));
87 * Improve error handling a bit. If we were given multiple IP addresses
88 * then return the old "no servers available" error, but point the user
89 * to -snoop (hopefully that's universal). Otherwise report a specific
94 snprintf(response
, len_response
, "no servers available (use -snoop "
97 snprintf(response
, len_response
, "Connection to \"%s\" failed: %s",
98 server
, strerror(errno
));