#ifndef NET_H #define NET_H #include #include #include class Net { // A network. It has a mask and an address. The mask is the mask size in // consecutive bits: net= 10.0.0.0 mask =8 means 0xa000000000 network and // 0xff000000 mask. Masked bits are always 0 in net. protected: int net; // Network int mask; // Mask // Clear the net to the mask. void normalize() { net &= 0xffffffff & (0xffffffff << (32 - mask)); } public: Net(const Net& n) : net(n.net), mask(n.mask) { normalize(); } // m is the number of consecutive 1 bits in the mask. Net(int n, int m) : net(n), mask(m) { normalize(); } // Parse a string of the form n.n.n.n/m Net(const std::string& s) : net(0), mask(0) { std::string::size_type mi = s.find("/"); if ( mi != std::string::npos ) mask = atoi(s.substr(mi+1).c_str()); else mask = 32; std::string::size_type p = 0; for (int i = 24; i >= 0; i -= 8 ) { int x = atoi(s.substr(p).c_str()); net |= (x) << i; if ( (p = s.find(".", p)) != std::string::npos) p++; } normalize(); } // Accessors int get_net() const { return net; } void set_net(int n) { net = n; normalize(); } int get_mask() const { return mask; } void set_mask(int m) { mask = m; normalize(); } // Output in n.n.n.n/m format. std::ostream& print(std::ostream& f) const { f << ( (net & 0xff000000) >> 24) << "."; f << ( (net & 0x00ff0000) >> 16) << "."; f << ( (net & 0x0000ff00) >> 8) << "."; f << ( (net & 0x000000ff)); f << "/" << mask; return f; } // True if the given net is inside this net using this net's mask bool inside(const Net& n) const { Net tn = Net(net, n.mask); return (tn.net ^ n.net) == 0; } // Standard operators bool operator==(const Net& n) const { return net == n.net && mask == n.mask; } bool operator<(const Net& n) const { return mask < n.mask || ( (mask == n.mask) && (net < n.net)); } }; // Convenient << defintion for output inline std::ostream& operator<<(std::ostream& f, const Net& n) { return n.print(f); } // A Net specialized to have a 32 bit mask and print without the / class Host : public Net { public: Host(const Host& h) : Net(h) { } Host(int h) : Net(h, 32) { } Host(const std::string& s) : Net(s) { } std::ostream& print(std::ostream& f) const { f << ( (net & 0xff000000) >> 24) << "."; f << ( (net & 0x00ff0000) >> 16) << "."; f << ( (net & 0x0000ff00) >> 8) << "."; f << ( (net & 0x000000ff)); return f; } }; // Convenient << defintion for output inline std::ostream& operator<<(std::ostream& f, const Host& n) { return n.print(f); } #endif