将 mac 地址转换为 Ruby 中的 IPv6 link 本地地址

Converting mac address to IPv6 link local address in Ruby

如何在 [=25] 中将 mac 地址如 00:16:3e:15:d3:a9 转换为 IPv6 link 本地地址(修改后的 EUI-64,如 fe80::216:3eff:fe15:d3a9) =]?

到目前为止,我有以下步骤:

mac = "00:16:3e:15:d3:a9"
mac.delete!(':')        # Delete colons
mac.insert(6, 'fffe')   # Insert ff:ee in the middle
mac = mac.scan(/.{4}/)  # Split into octets of 4

next step 将翻转第一个八位字节的第六位,我遇到了麻烦。

这是您的主要问题:Ruby 是一种面向对象的语言。您可以通过操纵丰富的结构化对象来创建程序,更准确地说,是让丰富的结构化对象操纵它们自己。

然而,你正在操纵 Strings。现在,当然,Strings 也是 Ruby 中的对象,但它们是表示 text 的对象,而不是表示 的对象IP 地址 或 EUI。

您应该至少将 IP 地址或 EUI 视为 数字,而不是文本,但实际上,您应该将它们视为丰富的, 结构化 IP 地址对象或 EUI 对象。

Ruby 实际上是 a library for manipulating IP addresses as part of its standard library.

下面是将这些地址视为数字 and/or 对象的示例:

require 'ipaddr'

eui48 = '00-16-3E-15-D3-A9'
# eliminate all delimiters, note that only ':' is not enough; the standard is '-', but '.' is also sometimes used
eui48 = eui48.gsub(/[^0-9a-zA-Z]/, '')
# parse the EUI-48 as a number
eui48 = eui48.to_i(16)

# split the EUI-48 into the OUI and the manufacturer-assigned parts
oui, assigned = eui48.divmod(1 << 24)

# append 16 zero bits to the OUI
left = oui << 16
# add the standard bit sequence
left += 0xfffe
# append 24 zero bits
left <<= 24

# now we have an EUI-64
eui64 = left + assigned

# flip bit index 57 to create a modified EUI-64
modified_eui64 = eui64 ^ 1 << 57

# the prefix for link-local IPv6 addresses is fe80::/10, link-local addresses are in the fe80::/64 network
prefix = IPAddr.new('fe80::/64')

# the suffix is based on our modified EUI-64
suffix = IPAddr.new(modified_eui64, Socket::AF_INET6)

# the final result is the bitwise logical OR of the prefix and suffix
link_local_ipv6 = prefix | suffix

# the IP address library knows how to correctly format an address according to RFC 5952 Section 4
link_local_ipv6.to_s
#=> 'fe80::216:3eff:fe15:d3a9'