From 28cc7b01800e3e2a46a995b2ca18b0d2d5cdc804 Mon Sep 17 00:00:00 2001 From: Nick Mathewson Date: Mon, 2 May 2011 16:43:11 -0400 Subject: Add a new "tor_sockaddr_to_str()" function It does what it says on the tin. It turns out I'll want this in a couple of places. --- src/common/address.c | 30 ++++++++++++++++++++++++++++++ src/common/address.h | 1 + 2 files changed, 31 insertions(+) diff --git a/src/common/address.c b/src/common/address.c index 34e109fcf4..1c725393d9 100644 --- a/src/common/address.c +++ b/src/common/address.c @@ -43,6 +43,9 @@ #ifdef HAVE_SYS_PARAM_H #include /* FreeBSD needs this to know what version it is */ #endif +#ifdef HAVE_SYS_UN_H +#include +#endif #include #include #include @@ -120,6 +123,33 @@ tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, return 0; } +/** Return a newly allocated string holding the address described in + * sa. AF_UNIX, AF_UNSPEC, AF_INET, and AF_INET6 are supported. */ +char * +tor_sockaddr_to_str(const struct sockaddr *sa) +{ + char address[TOR_ADDR_BUF_LEN]; + char *result; + tor_addr_t addr; + uint16_t port; +#ifdef HAVE_SYS_UN_H + if (sa->sa_family == AF_UNIX) { + struct sockaddr_un *s_un = (struct sockaddr_un *)sa; + tor_asprintf(&result, "unix:%s", s_un->sun_path); + return result; + } +#endif + if (sa->sa_family == AF_UNSPEC) + return tor_strdup("unspec"); + + if (tor_addr_from_sockaddr(&addr, sa, &port) < 0) + return NULL; + if (! tor_addr_to_str(address, &addr, sizeof(address), 1)) + return NULL; + tor_asprintf(&result, "%s:%d", address, (int)port); + return result; +} + /** Set address a to the unspecified address. This address belongs to * no family. */ void diff --git a/src/common/address.h b/src/common/address.h index d05a3de2e7..9a7656f69b 100644 --- a/src/common/address.h +++ b/src/common/address.h @@ -44,6 +44,7 @@ socklen_t tor_addr_to_sockaddr(const tor_addr_t *a, uint16_t port, int tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, uint16_t *port_out); void tor_addr_make_unspec(tor_addr_t *a); +char *tor_sockaddr_to_str(const struct sockaddr *sa); /** Return an in6_addr* equivalent to a, or NULL if a is not * an IPv6 address. */ -- cgit v1.2.3-54-g00ecf