From e6f19319684b4b1755b397833b229c9a5970724a Mon Sep 17 00:00:00 2001 From: Thadeu Lima de Souza Cascardo Date: Mon, 7 Oct 2013 08:32:47 -0300 Subject: [PATCH] Get the address for a friend --- friend.c | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/friend.c b/friend.c index 58e7bc5..753a588 100644 --- a/friend.c +++ b/friend.c @@ -26,14 +26,12 @@ #include #include -static int connect_friend(struct sockaddr *saddr, char *address, char *port, int *c) +static int connect_friend(struct sockaddr **saddr, char *address, char *port) { struct addrinfo *addresses; struct addrinfo *addr; struct addrinfo hint; int r; - int fd = *c = -1; - int i; memset(&hint, 0, sizeof(hint)); hint.ai_family = AF_UNSPEC; hint.ai_socktype = SOCK_STREAM; @@ -43,17 +41,16 @@ static int connect_friend(struct sockaddr *saddr, char *address, char *port, int if (r) { return r; } - for (addr = addresses; addr != NULL; addr = addr->ai_next) { - fd = socket(addr->ai_family, addr->ai_socktype, - addr->ai_protocol); - if (fd >= 0) - break; - close(fd); - fd = -1; + if (addresses != NULL) { + *saddr = malloc(addresses->ai_addrlen); + if (!*saddr) { + r = -1; + } else { + memcpy(*saddr, addresses->ai_addr, addresses->ai_addrlen); + } } freeaddrinfo(addresses); - *c = fd; - if (fd == -1) + if (r == -1) return EAI_SYSTEM; return 0; } @@ -107,7 +104,7 @@ int cache_add_friend(struct cache *cache, char *friend, char *address, char *por tfriend->name = friend; tfriend->address = address; tfriend->port = port; - tfriend->saddr = NULL; + connect_friend(&tfriend->saddr, tfriend->address, tfriend->port); return 0; } -- 2.20.1