From 83966b369d2fa105a58a35830f75662e18273965 Mon Sep 17 00:00:00 2001 From: Rich Felker Date: Tue, 25 Jun 2013 21:15:27 -0400 Subject: [PATCH] add ether_aton[_r] and ether_ntoa[_r] functions based on patch by Strake with minor stylistic changes, and combined into a single file. this patch remained open for a long time due to some question as to whether ether_aton would be better implemented in terms of sscanf, and it's time something was committed, so here it is. --- include/netinet/ether.h | 14 ++++++++++++++ src/network/ether.c | 43 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 include/netinet/ether.h create mode 100644 src/network/ether.c diff --git a/include/netinet/ether.h b/include/netinet/ether.h new file mode 100644 index 00000000..c5179d5e --- /dev/null +++ b/include/netinet/ether.h @@ -0,0 +1,14 @@ +#ifndef _NETINET_ETHER_H +#define _NETINET_ETHER_H + +#include + +char *ether_ntoa (const struct ether_addr *); + +struct ether_addr *ether_aton (const char *); + +char *ether_ntoa_r (const struct ether_addr *, char *); + +struct ether_addr *ether_aton_r (const char *, struct ether_addr *); + +#endif diff --git a/src/network/ether.c b/src/network/ether.c new file mode 100644 index 00000000..ac55411a --- /dev/null +++ b/src/network/ether.c @@ -0,0 +1,43 @@ +#include +#include +#include + +struct ether_addr *ether_aton_r (const char *x, struct ether_addr *p_a) +{ + struct ether_addr a; + char *y; + for (int ii = 0; ii < 6; ii++) { + unsigned long int n; + if (ii != 0) { + if (x[0] != ':') return 0; /* bad format */ + else x++; + } + n = strtoul (x, &y, 16); + x = y; + if (n > 0xFF) return 0; /* bad byte */ + a.ether_addr_octet[ii] = n; + } + if (x[0] != 0) return 0; /* bad format */ + *p_a = a; + return p_a; +} + +struct ether_addr *ether_aton (const char *x) +{ + static struct ether_addr a; + return ether_aton_r (x, &a); +} + +char *ether_ntoa_r (const struct ether_addr *p_a, char *x) { + char *y; + y = x; + for (int ii = 0; ii < 6; ii++) { + x += sprintf (x, ii == 0 ? "%.2X" : ":%.2X", p_a->ether_addr_octet[ii]); + } + return y; +} + +char *ether_ntoa (const struct ether_addr *p_a) { + static char x[18]; + return ether_ntoa_r (p_a, x); +} -- 2.25.1