【问题标题】:How to parse IP address blocks IPv4 / IPv6如何解析 IP 地址块 IPv4 / IPv6
【发布时间】:2013-07-02 06:24:00
【问题描述】:

我正在创建一个IP地址类包装器,我想根据RFC 5735 Section 4 - Special Use IPv4 Addresses区分地址类型。

我想要

  • 能够测试地址是否在其中一个块内。
  • 展开一个块,所以我在返回时得到一个 IPAddress 对象数组。

如果有人可以通过小示例代码帮助我,或者将我指向现有代码,我将不胜感激。可悲的是,我发现我的大脑无法理解这个主题的复杂性,这就是我特别要求示例代码的原因。我知道这样要求源代码是不礼貌的,我很抱歉。

【问题讨论】:

  • 你至少尝试过什么?

标签: c++ ip-address


【解决方案1】:

在提出统一的 IP 地址表示时,重要的是要认识到 IPv4 地址占用 4 个字节,而 IPv6 地址需要 16 个字节。一个简单的包装器实现将使用联合加枚举鉴别器来指示地址类型。幸运的是,这不是必需的,因为在 IPv6 地址存在 IPv4 地址的明确表示。牢记这一点,您的 IP 地址包装类可能如下所示:

class address
{
  /// Top 96 bits of v4-mapped-addr.
  static std::array<uint8_t, 12> const v4_mapped_prefix =
    {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff }};

public:
  address() = default;

  bool is_v4() const
  {
    return std::memcmp(&bytes_, &v4_mapped_prefix, 12) == 0;
  }

private:
  std::array<uint8_t, 16> bytes_;
};

现在要检查您是否有某一类地址,您可以随意添加成员函数。以下是环回、广播和多播的示例:

bool is_loopback() const
{
  if (is_v4())
    return bytes_[12] == 127;
  else
    return ((bytes_[0] == 0) && (bytes_[1] == 0) &&
            (bytes_[2] == 0) && (bytes_[3] == 0) &&
            (bytes_[4] == 0) && (bytes_[5] == 0) &&
            (bytes_[6] == 0) && (bytes_[7] == 0) &&
            (bytes_[8] == 0) && (bytes_[9] == 0) &&
            (bytes_[10] == 0) && (bytes_[11] == 0) &&
            (bytes_[12] == 0) && (bytes_[13] == 0) &&
            (bytes_[14] == 0) && (bytes_[15] == 1));
}

bool is_broadcast() const
{
  return is_v4() &&
    bytes_[12] == 0xff && bytes_[13] == 0xff &&
    bytes_[14] == 0xff && bytes_[15] == 0xff;
}

bool is_multicast() const
{
  return is_v4() ? bytes_[12] == 224 : bytes_[0] == 0xff;
}

【讨论】:

  • 谢谢,这足以让我的大脑正常工作,谢谢!
猜你喜欢
  • 2012-12-25
  • 1970-01-01
  • 2011-06-09
  • 1970-01-01
  • 2011-02-16
  • 2019-07-13
  • 1970-01-01
  • 2011-11-09
  • 2013-09-18
相关资源
最近更新 更多