summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorVadim Kochan <vadim4j@gmail.com>2016-01-26 22:25:03 +0200
committerTobias Klauser <tklauser@distanz.ch>2016-01-28 16:15:11 +0100
commit5ad97d9ef3f77a246a588f4256d92f831e542f5d (patch)
tree952674cb0dc0918b80b1701b3c5c84d949305e42
parent11a7670eb559580885e096216a494d2c96702645 (diff)
str: Add str2mac helper function
Add function to convert a string in the format xx:xx:xx:xx:xx:xx to a MAC address byte array. Signed-off-by: Vadim Kochan <vadim4j@gmail.com> [tk: Add len parameter and error out on too short buffers] Signed-off-by: Tobias Klauser <tklauser@distanz.ch>
-rw-r--r--str.c29
-rw-r--r--str.h3
2 files changed, 32 insertions, 0 deletions
diff --git a/str.c b/str.c
index e4d8722..cfee03f 100644
--- a/str.c
+++ b/str.c
@@ -7,6 +7,7 @@
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
+#include <arpa/inet.h>
#include "str.h"
#include "die.h"
@@ -129,3 +130,31 @@ void argv_free(char **argv)
free(tmp);
}
+
+int str2mac(const char *str, uint8_t *mac, size_t len)
+{
+ int i, count;
+ unsigned int tmp[6];
+
+ if (!str)
+ return -EINVAL;
+ if (len < 6)
+ return -ENOSPC;
+
+ count = sscanf(str, "%02X:%02X:%02X:%02X:%02X:%02X",
+ &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5]);
+
+ if (errno || count != 6)
+ count = sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
+ &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5]);
+
+ if (count != 6)
+ return -EINVAL;
+ if (errno)
+ return -errno;
+
+ for (i = 0; i < 6; i++)
+ mac[i] = (uint8_t)tmp[i];
+
+ return 0;
+}
diff --git a/str.h b/str.h
index 3ffb2b9..7879af6 100644
--- a/str.h
+++ b/str.h
@@ -1,6 +1,8 @@
#ifndef STR_H
#define STR_H
+#include <stdlib.h>
+
#include "built_in.h"
extern size_t strlcpy(char *dest, const char *src, size_t size);
@@ -11,5 +13,6 @@ extern noinline void *xmemset(void *s, int c, size_t n);
extern char *argv2str(int startind, int argc, char **argv);
extern char **argv_insert(char **argv, size_t *count, const char *str);
extern void argv_free(char **argv);
+extern int str2mac(const char *str, uint8_t *mac, size_t len);
#endif /* STR_H */