Refactor getaddrinfo error reporting.

This commit is contained in:
Sam Hocevar 2021-02-17 08:21:58 +01:00
parent e3b47d086a
commit 1060048fe8
3 changed files with 18 additions and 12 deletions

View File

@ -10,6 +10,7 @@
# include <config.h>
#endif
#include <stdio.h>
#include "net.h"
void setSocketDefaults(SOCKET fd) {
@ -32,13 +33,23 @@ void setSocketDefaults(SOCKET fd) {
#endif
}
struct addrinfo getAddrInfoHint(int protocol) {
return (struct addrinfo) {
int getAddrInfoWithProto(char *address, char *port, int protocol, struct addrinfo **ai)
{
struct addrinfo hints = {
.ai_family = AF_UNSPEC,
.ai_protocol = protocol,
.ai_socktype = protocol == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM,
.ai_flags = AI_PASSIVE,
};
int ret = getaddrinfo(address, port, &hints, ai);
if (ret != 0) {
fprintf(stderr, "rinetd: cannot resolve host \"%s\" port %s "
"(getaddrinfo() error: %s)\n",
address, port ? port : "<null>", gai_strerror(ret));
}
return ret;
}
int sameSocketAddress(struct sockaddr_storage *a, struct sockaddr_storage *b) {

View File

@ -85,6 +85,6 @@ static inline int GetLastError(void) {
#endif /* _WIN32 */
void setSocketDefaults(SOCKET fd);
struct addrinfo getAddrInfoHint(int protocol);
int sameSocketAddress(struct sockaddr_storage *a, struct sockaddr_storage *b);
int getAddrInfoWithProto(char *address, char *port, int protocol, struct addrinfo **ai);
uint16_t getPort(struct addrinfo* ai);

View File

@ -267,10 +267,9 @@ void addServer(char *bindAddress, char *bindPort, int bindProtocol,
};
/* Make a server socket */
struct addrinfo hints = getAddrInfoHint(bindProtocol), *ai;
int ret = getaddrinfo(bindAddress, bindPort, &hints, &ai);
struct addrinfo *ai;
int ret = getAddrInfoWithProto(bindAddress, bindPort, bindProtocol, &ai);
if (ret != 0) {
fprintf(stderr, "rinetd: getaddrinfo error: %s\n", gai_strerror(ret));
exit(1);
}
@ -308,10 +307,8 @@ void addServer(char *bindAddress, char *bindPort, int bindProtocol,
si.fromAddrInfo = ai;
/* Resolve destination address. */
hints = getAddrInfoHint(connectProtocol);
ret = getaddrinfo(connectAddress, connectPort, &hints, &ai);
ret = getAddrInfoWithProto(connectAddress, connectPort, connectProtocol, &ai);
if (ret != 0) {
fprintf(stderr, "rinetd: getaddrinfo error: %s\n", gai_strerror(ret));
freeaddrinfo(si.fromAddrInfo);
closesocket(si.fd);
exit(1);
@ -320,10 +317,8 @@ void addServer(char *bindAddress, char *bindPort, int bindProtocol,
/* Resolve source address if applicable. */
if (sourceAddress) {
hints = getAddrInfoHint(connectProtocol);
ret = getaddrinfo(sourceAddress, NULL, &hints, &ai);
ret = getAddrInfoWithProto(sourceAddress, NULL, connectProtocol, &ai);
if (ret != 0) {
fprintf(stderr, "rinetd: getaddrinfo error: %s\n", gai_strerror(ret));
freeaddrinfo(si.fromAddrInfo);
freeaddrinfo(si.toAddrInfo);
exit(1);