Add a more flexible version of hwaddr_aton: hwaddr_aton2()
authorJouni Malinen <j@w1.fi>
Tue, 6 Apr 2010 07:37:13 +0000 (10:37 +0300)
committerJouni Malinen <j@w1.fi>
Tue, 6 Apr 2010 07:37:13 +0000 (10:37 +0300)
This version of the MAC address parser allows number of different
string formats for the address (e.g., 00:11:22:33:44:55, 0011.2233.4455,
001122334455, 00-11-22-33-44-55). It returns the number of characters
used from the input string in case of success.

src/utils/common.c
src/utils/common.h

index 9a46ebe..1b8ea80 100644 (file)
@@ -43,7 +43,7 @@ static int hex2byte(const char *hex)
 
 
 /**
- * hwaddr_aton - Convert ASCII string to MAC address
+ * hwaddr_aton - Convert ASCII string to MAC address (colon-delimited format)
  * @txt: MAC address as a string (e.g., "00:11:22:33:44:55")
  * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
  * Returns: 0 on success, -1 on failure (e.g., string not a MAC address)
@@ -71,6 +71,36 @@ int hwaddr_aton(const char *txt, u8 *addr)
 
 
 /**
+ * hwaddr_aton2 - Convert ASCII string to MAC address (in any known format)
+ * @txt: MAC address as a string (e.g., 00:11:22:33:44:55 or 0011.2233.4455)
+ * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
+ * Returns: Characters used (> 0) on success, -1 on failure
+ */
+int hwaddr_aton2(const char *txt, u8 *addr)
+{
+       int i;
+       const char *pos = txt;
+
+       for (i = 0; i < 6; i++) {
+               int a, b;
+
+               while (*pos == ':' || *pos == '.' || *pos == '-')
+                       pos++;
+
+               a = hex2num(*pos++);
+               if (a < 0)
+                       return -1;
+               b = hex2num(*pos++);
+               if (b < 0)
+                       return -1;
+               *addr++ = (a << 4) | b;
+       }
+
+       return pos - txt;
+}
+
+
+/**
  * hexstr2bin - Convert ASCII hex string into binary data
  * @hex: ASCII hex string (e.g., "01ab")
  * @buf: Buffer for the binary data
index 9abda59..f17bf69 100644 (file)
@@ -436,6 +436,7 @@ typedef u64 __bitwise le64;
 #endif /* __must_check */
 
 int hwaddr_aton(const char *txt, u8 *addr);
+int hwaddr_aton2(const char *txt, u8 *addr);
 int hexstr2bin(const char *hex, u8 *buf, size_t len);
 void inc_byte_array(u8 *counter, size_t len);
 void wpa_get_ntp_timestamp(u8 *buf);