官术网_书友最值得收藏!

16. Enumerating IPv4 addresses in a range

To be able to enumerate IPv4 addresses in a given range, it should first be possible to compare IPv4 values. Therefore, we should implement at least operator<, but the following listing contains implementation for all comparison operators: ==, !=, <, >, <=, and >=. Also, in order to increment an IPv4 value, implementations for both the prefix and postfix operator++ are provided. The following code is an extension of the IPv4 class from the previous problem:

ipv4& operator++()
{
*this = ipv4(1 + to_ulong());
return *this;
}

ipv4& operator++(int)
{
ipv4 result(*this);
++(*this);
return *this;
}

friend bool operator==(ipv4 const & a1, ipv4 const & a2) noexcept
{
return a1.data == a2.data;
}

friend bool operator!=(ipv4 const & a1, ipv4 const & a2) noexcept
{
return !(a1 == a2);
}

friend bool operator<(ipv4 const & a1, ipv4 const & a2) noexcept
{
return a1.to_ulong() < a2.to_ulong();
}

friend bool operator>(ipv4 const & a1, ipv4 const & a2) noexcept
{
return a2 < a1;
}

friend bool operator<=(ipv4 const & a1, ipv4 const & a2) noexcept
{
return !(a1 > a2);
}

friend bool operator>=(ipv4 const & a1, ipv4 const & a2) noexcept
{
return !(a1 < a2);
}

With these changes to the ipv4 class from the previous problem, we can write the following program:

int main()
{
std::cout << "input range: ";
ipv4 a1, a2;
std::cin >> a1 >> a2;
if (a2 > a1)
{
for (ipv4 a = a1; a <= a2; a++)
{
std::cout << a << std::endl;
}
}
else
{
std::cerr << "invalid range!" << std::endl;
}
}
主站蜘蛛池模板: 灵璧县| 灵璧县| 农安县| 梅州市| 新泰市| 临猗县| 大渡口区| 增城市| 鄂伦春自治旗| 兴和县| 渝中区| 三门县| 故城县| 洪雅县| 鄯善县| 牡丹江市| 屏东市| 宣城市| 内江市| 民和| 长岭县| 仙桃市| 湄潭县| 阜城县| 栾城县| 英山县| 华容县| 合川市| 松溪县| 康马县| 驻马店市| 黎平县| 阿图什市| 合肥市| 诏安县| 嵊州市| 泗阳县| 汝南县| 蕉岭县| 富裕县| 沙河市|