From 60989f1ca3dedbfc379477ea3d73ecfbbafde8f8 Mon Sep 17 00:00:00 2001 From: Hannes Reinecke Date: Mon, 26 Aug 2013 12:57:25 +0200 Subject: ping, ping6: Lookup host name only once If we're sending multiple ping we don't need to lookup the host over and over again. Signed-off-by: Hannes Reinecke --- ping.c | 15 +++++++++++---- ping6.c | 17 ++++++++++++++--- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/ping.c b/ping.c index c0366cd..71b445d 100644 --- a/ping.c +++ b/ping.c @@ -1263,13 +1263,20 @@ void pr_iph(struct iphdr *ip) char * pr_addr(__u32 addr) { - struct hostent *hp; + struct hostent *hp = NULL; static char buf[4096]; + static __u32 last_addr; in_pr_addr = !setjmp(pr_addr_jmp); - if (exiting || (options & F_NUMERIC) || - !(hp = gethostbyaddr((char *)&addr, 4, AF_INET))) + if (exiting || (options & F_NUMERIC)) { + if (buf[0] && addr == last_addr) { + in_pr_addr = 0; + return buf; + } + hp = gethostbyaddr((char *)&addr, 4, AF_INET); + } + if (hp) sprintf(buf, "%s", inet_ntoa(*(struct in_addr *)&addr)); else { char *s; @@ -1287,7 +1294,7 @@ pr_addr(__u32 addr) } in_pr_addr = 0; - + last_addr = addr; return(buf); } diff --git a/ping6.c b/ping6.c index c39864d..e8f1133 100644 --- a/ping6.c +++ b/ping6.c @@ -1793,7 +1793,9 @@ void install_filter(void) char * pr_addr(struct in6_addr *addr) { struct hostent *hp = NULL; + static struct in6_addr last_addr; static char *s; + static char buf[4096]; #ifdef USE_IDN free(s); @@ -1801,9 +1803,12 @@ char * pr_addr(struct in6_addr *addr) in_pr_addr = !setjmp(pr_addr_jmp); - if (!(exiting || options&F_NUMERIC)) - hp = gethostbyaddr((__u8*)addr, sizeof(struct in6_addr), AF_INET6); + if (!(exiting || options&F_NUMERIC)) { + if (buf[0] && !memcmp(&last_addr, addr, sizeof(*addr))) + return buf; + hp = gethostbyaddr((__u8*)addr, sizeof(struct in6_addr), AF_INET6); + } in_pr_addr = 0; if (!hp @@ -1813,7 +1818,13 @@ char * pr_addr(struct in6_addr *addr) ) s = NULL; - return hp ? (s ? s : hp->h_name) : pr_addr_n(addr); + if (hp && strlen(hp->h_name) < sizeof(buf)) { + strcpy(buf, hp->h_name); + } else { + inet_ntop(AF_INET6, addr, buf, sizeof(buf)); + } + last_addr = *addr; + return buf; } char * pr_addr_n(struct in6_addr *addr) -- 1.8.1.4