File:  [Isaki's NoNo m68k/m88k emulator] / nono / lib / macaddr.cpp
Revision 1.1.1.2 (vendor branch): download - view: text, annotated - select for diffs
Wed Apr 29 17:05:35 2026 UTC (2 months, 3 weeks ago) by root
Branches: MAIN, Isaki
CVS tags: v027, v026, v025, v024, v023, v022, HEAD
nono 1.2.0

//
// nono
// Copyright (C) 2021 nono project
// Licensed under nono-license.txt
//

//
// MAC アドレス
//

#include "macaddr.h"
#include "mystring.h"
#include <random>

// MAC アドレスを適当に生成する。
// 02:00:01 はローカルだし割り当てもされてなさそうなので使っちゃえ。
// 下3バイトは乱数。
void
MacAddr::Generate()
{
	std::random_device rnd;
	uint32 x = rnd();

	(*this)[0] = 0x02;
	(*this)[1] = 0x00;
	(*this)[2] = 0x01;
	(*this)[3] = (x >> 16) & 0xff;
	(*this)[4] = (x >>  8) & 0xff;
	(*this)[5] = x & 0xff;
}

// 文字列から MAC アドレスを作成する。"HH:HH:HH:HH:HH:HH" 形式のみ。
// 成功すれば true を返す。
bool
MacAddr::FromString(const std::string& src)
{
	const char *p;
	char *e;

	p = src.data();
	for (int i = 0; ; ) {
		unsigned long val = strtoul(p, &e, 16);

		if (p == e) {
			return false;
		}
		if (val > 0xff) {
			return false;
		}
		(*this)[i++] = val;
		p = e;

		// 最後だけ ':' をチェックしないので
		if (i == 6) {
			break;
		}

		if (*p++ != ':') {
			return false;
		}
	}
	if (*p != '\0') {
		return false;
	}
	return true;
}

// 区切り文字なしの文字列形式を返す。主に ROM 埋め込み用で英字は大文字。
// 01:23:AB なら "0123AB" のような感じ。
std::string
MacAddr::ToString() const
{
	return string_format("%02X%02X%02X%02X%02X%02X",
		(*this)[0],
		(*this)[1],
		(*this)[2],
		(*this)[3],
		(*this)[4],
		(*this)[5]);
}

// sep を区切り文字とする文字列形式を返す。主に表示用で英字は小文字。
// 01:23:AB で sep = ":" なら "01:23:ab" のような感じ。
std::string
MacAddr::ToString(char sep) const
{
	return string_format("%02x:%02x:%02x:%02x:%02x:%02x",
		(*this)[0],
		(*this)[1],
		(*this)[2],
		(*this)[3],
		(*this)[4],
		(*this)[5]);
}

unix.superglobalmegacorp.com

This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.