|
|
1.1 root 1: //
2: // nono
3: // Copyright (C) 2021 nono project
4: // Licensed under nono-license.txt
5: //
6:
7: //
8: // MAC アドレス
9: //
10:
11: #include "macaddr.h"
12: #include "mystring.h"
13: #include <random>
14:
15: // この MAC アドレスが 00:00:00:00:00:00 なら true を返す
16: bool
17: macaddr_t::Empty() const
18: {
19: for (const auto v : *this) {
20: if (v != 0) {
21: return false;
22: }
23: }
24: return true;
25: }
26:
27: // MAC アドレスを適当に生成する。
28: // 02:00:01 はローカルだし割り当てもされてなさそうなので使っちゃえ。
29: // 下3バイトは乱数。
30: void
31: macaddr_t::Generate()
32: {
33: std::random_device rnd;
34: uint32 x = rnd();
35:
36: (*this)[0] = 0x02;
37: (*this)[1] = 0x00;
38: (*this)[2] = 0x01;
39: (*this)[3] = (x >> 16) & 0xff;
40: (*this)[4] = (x >> 8) & 0xff;
41: (*this)[5] = x & 0xff;
42: }
43:
44: // 文字列から MAC アドレスを作成する。"HH:HH:HH:HH:HH:HH" 形式のみ。
45: // 成功すれば true を返す。
46: bool
47: macaddr_t::FromString(const std::string& src)
48: {
49: const char *p;
50: char *e;
51:
52: p = src.data();
53: for (int i = 0; ; ) {
54: unsigned long val = strtoul(p, &e, 16);
55:
56: if (p == e) {
57: return false;
58: }
59: if (val > 0xff) {
60: return false;
61: }
62: (*this)[i++] = val;
63: p = e;
64:
65: // 最後だけ ':' をチェックしないので
66: if (i == 6) {
67: break;
68: }
69:
70: if (*p++ != ':') {
71: return false;
72: }
73: }
74: if (*p != '\0') {
75: return false;
76: }
77: return true;
78: }
79:
80: // 区切り文字なしの文字列形式を返す。主に ROM 埋め込み用で英字は大文字。
81: // 01:23:AB なら "0123AB" のような感じ。
82: std::string
83: macaddr_t::ToString() const
84: {
85: return string_format("%02X%02X%02X%02X%02X%02X",
86: (*this)[0],
87: (*this)[1],
88: (*this)[2],
89: (*this)[3],
90: (*this)[4],
91: (*this)[5]);
92: }
93:
94: // sep を区切り文字とする文字列形式を返す。主に表示用で英字は小文字。
95: // 01:23:AB で sep = ":" なら "01:23:ab" のような感じ。
96: std::string
97: macaddr_t::ToString(char sep) const
98: {
99: return string_format("%02x:%02x:%02x:%02x:%02x:%02x",
100: (*this)[0],
101: (*this)[1],
102: (*this)[2],
103: (*this)[3],
104: (*this)[4],
105: (*this)[5]);
106: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.