]>
diplodocus.org Git - nmh/blob - sbr/client.c
8d390a816510b54a7ee6c1c89209ec07378ebbbf
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.
13 #include <sys/socket.h>
14 #include <netinet/in.h>
16 #include <arpa/inet.h>
21 client (char *server
, char *service
, char *response
, int len_response
,
25 struct addrinfo hints
, *res
, *ai
;
27 if (!server
|| *server
== '\0') {
28 snprintf(response
, len_response
, "Internal error: NULL server name "
29 "passed to client()");
35 hints
.ai_flags
= AI_ADDRCONFIG
;
37 hints
.ai_family
= PF_UNSPEC
;
38 hints
.ai_socktype
= SOCK_STREAM
;
41 fprintf(stderr
, "Trying to connect to \"%s\" ...\n", server
);
44 rc
= getaddrinfo(server
, service
, &hints
, &res
);
47 snprintf(response
, len_response
, "Lookup of \"%s\" failed: %s",
48 server
, gai_strerror(rc
));
52 for (ai
= res
; ai
!= NULL
; ai
= ai
->ai_next
) {
54 char address
[NI_MAXHOST
];
55 char port
[NI_MAXSERV
];
57 rc
= getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, address
,
58 sizeof(address
), port
, sizeof port
,
59 NI_NUMERICHOST
| NI_NUMERICSERV
);
61 fprintf(stderr
, "Connecting to %s:%s...\n",
62 rc
? "unknown" : address
, rc
? "--" : port
);
65 sd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
69 fprintf(stderr
, "socket() failed: %s\n", strerror(errno
));
74 if (connect(sd
, ai
->ai_addr
, ai
->ai_addrlen
) == 0) {
79 flags
= fcntl(sd
, F_GETFD
, 0);
82 fcntl(sd
, F_SETFD
, flags
| FD_CLOEXEC
);
90 fprintf(stderr
, "Connection failed: %s\n", strerror(errno
));
97 * Improve error handling a bit. If we were given multiple IP addresses
98 * then return the old "no servers available" error, but point the user
99 * to -snoop (hopefully that's universal). Otherwise report a specific
104 snprintf(response
, len_response
, "no servers available (use -snoop "
107 char port
[NI_MAXSERV
];
109 if (getnameinfo(res
->ai_addr
, res
->ai_addrlen
, NULL
, 0, port
,
110 sizeof port
, NI_NUMERICSERV
)) {
111 strncpy(port
, "unknown", sizeof port
);
112 port
[sizeof(port
) - 1] = '\0';
115 snprintf(response
, len_response
, "Connection to \"%s:%s\" failed: %s",
116 server
, port
, strerror(errno
));