blob: af11a3a4fd7ff195c7a74b722994336854cbdf30 [file] [log] [blame]
Davide Pesavento56fb5972014-03-12 06:18:37 +01001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (C) 2014 Named Data Networking Project
4 * See COPYING for copyright and distribution information.
5 */
6
7#include "ethernet.hpp"
8
9#include <stdio.h>
10
11namespace nfd {
12namespace ethernet {
13
14std::string
15Address::toString(char sep) const
16{
17 char s[18]; // 12 digits + 5 separators + null terminator
18 ::snprintf(s, sizeof(s), "%02x%c%02x%c%02x%c%02x%c%02x%c%02x",
19 elems[0], sep, elems[1], sep, elems[2], sep,
20 elems[3], sep, elems[4], sep, elems[5]);
21 return std::string(s);
22}
23
24Address
25Address::fromString(const std::string& str)
26{
27 Address a;
28 int n, ret;
29
30 // colon-separated
31 ret = ::sscanf(str.c_str(), "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx%n",
32 &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &n);
33 if (ret >= 6 && str.c_str()[n] == '\0')
34 return a;
35
36 // dash-separated
37 ret = ::sscanf(str.c_str(), "%hhx-%hhx-%hhx-%hhx-%hhx-%hhx%n",
38 &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &n);
39 if (ret >= 6 && str.c_str()[n] == '\0')
40 return a;
41
42 return Address();
43}
44
45std::ostream&
46operator<<(std::ostream& o, const Address& a)
47{
48 return o << a.toString();
49}
50
51} // namespace ethernet
52} // namespace nfd