- The Modern C++ Challenge
- Marius Bancila
- 299字
- 2021-06-25 22:01:26
15. IPv4 data type
The problem requires writing a class to represent an IPv4 address. This is a 32-bit value, usually represented in decimal dotted format, such as 168.192.0.100; each part of it is an 8-bit value, ranging from 0 to 255. For easy representation and handling, we can use four unsigned char to store the address value. Such a value could be constructed either from four unsigned char or from an unsigned long. In order to be able to read a value directly from the console (or any other input stream) and be able to write the value to the console (or any other output stream), we have to overload operator>> and operator<<. The following listing shows a minimal implementation that can meet the requested functionality:
class ipv4
{
std::array<unsigned char, 4> data;
public:
constexpr ipv4() : data{ {0} } {}
constexpr ipv4(unsigned char const a, unsigned char const b,
unsigned char const c, unsigned char const d):
data{{a,b,c,d}} {}
explicit constexpr ipv4(unsigned long a) :
data{ { static_cast<unsigned char>((a >> 24) & 0xFF),
static_cast<unsigned char>((a >> 16) & 0xFF),
static_cast<unsigned char>((a >> 8) & 0xFF),
static_cast<unsigned char>(a & 0xFF) } } {}
ipv4(ipv4 const & other) noexcept : data(other.data) {}
ipv4& operator=(ipv4 const & other) noexcept
{
data = other.data;
return *this;
}
std::string to_string() const
{
std::stringstream sstr;
sstr << *this;
return sstr.str();
}
constexpr unsigned long to_ulong() const noexcept
{
return (static_cast<unsigned long>(data[0]) << 24) |
(static_cast<unsigned long>(data[1]) << 16) |
(static_cast<unsigned long>(data[2]) << 8) |
static_cast<unsigned long>(data[3]);
}
friend std::ostream& operator<<(std::ostream& os, const ipv4& a)
{
os << static_cast<int>(a.data[0]) << '.'
<< static_cast<int>(a.data[1]) << '.'
<< static_cast<int>(a.data[2]) << '.'
<< static_cast<int>(a.data[3]);
return os;
}
friend std::istream& operator>>(std::istream& is, ipv4& a)
{
char d1, d2, d3;
int b1, b2, b3, b4;
is >> b1 >> d1 >> b2 >> d2 >> b3 >> d3 >> b4;
if (d1 == '.' && d2 == '.' && d3 == '.')
a = ipv4(b1, b2, b3, b4);
else
is.setstate(std::ios_base::failbit);
return is;
}
};
The ipv4 class can be used as follows:
int main()
{
ipv4 address(168, 192, 0, 1);
std::cout << address << std::endl;
ipv4 ip;
std::cout << ip << std::endl;
std::cin >> ip;
if(!std::cin.fail())
std::cout << ip << std::endl;
}
- Pandas Cookbook
- AngularJS Web Application Development Blueprints
- Python Game Programming By Example
- 羅克韋爾ControlLogix系統應用技術
- Mastering Python Networking
- PySide GUI Application Development(Second Edition)
- Oracle從入門到精通(第5版)
- C語言程序設計上機指導與習題解答(第2版)
- Learning YARN
- Learning Modular Java Programming
- Nagios Core Administration Cookbook(Second Edition)
- Building Slack Bots
- Learning Bootstrap 4(Second Edition)
- Hack與HHVM權威指南
- 軟件測試技術