diff --git a/include/hwaddress.h b/include/hwaddress.h index dc3d981..9a485b2 100644 --- a/include/hwaddress.h +++ b/include/hwaddress.h @@ -51,7 +51,8 @@ public: convert(address, buffer); } - HWAddress(const char *address) { + template + HWAddress(const char (&address)[i]) { convert(address, buffer); } @@ -105,6 +106,11 @@ public: ); return os << to_string(addr.buffer[HWAddress::address_size-1]); } + + template + OutputIterator copy(OutputIterator iter) { + return std::copy(begin(), end(), iter); + } private: template static void convert(const std::string &hw_addr, OutputIterator output); diff --git a/include/ipaddress.h b/include/ipaddress.h index 858d011..71676e7 100644 --- a/include/ipaddress.h +++ b/include/ipaddress.h @@ -31,7 +31,12 @@ namespace Tins { public: IPv4Address(uint32_t ip = 0); IPv4Address(const std::string &ip); - IPv4Address(const char *ip); + + template + IPv4Address(const char (&ip)[n]) + : ip_addr(ip_to_int(ip)) { + + } IPv4Address &operator=(uint32_t ip); IPv4Address &operator=(const std::string &ip); @@ -48,6 +53,8 @@ namespace Tins { return output << (std::string)addr; } private: + uint32_t ip_to_int(const std::string &ip); + uint32_t ip_addr; }; }; diff --git a/src/ipaddress.cpp b/src/ipaddress.cpp index 25a5f00..ee80f95 100644 --- a/src/ipaddress.cpp +++ b/src/ipaddress.cpp @@ -19,6 +19,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +#include #include "ipaddress.h" #include "utils.h" @@ -34,10 +35,10 @@ IPv4Address::IPv4Address(const std::string &ip) } -IPv4Address::IPv4Address(const char *ip) +/*IPv4Address::IPv4Address(const char *ip) : ip_addr(Utils::ip_to_int(ip)) { -} +}*/ IPv4Address &IPv4Address::operator=(uint32_t ip) { ip_addr = ip; @@ -60,4 +61,28 @@ IPv4Address::operator std::string() const { bool IPv4Address::operator==(const std::string &rhs) const { return ip_addr == Utils::ip_to_int(rhs); } + +uint32_t IPv4Address::ip_to_int(const string &ip) { + uint32_t result(0), i(0), end, bytes_found(0); + while(i < ip.size() && bytes_found < 4) { + uint16_t this_byte(0); + end = i + 3; + while(i < ip.size() && i < end && ip[i] != '.') { + if(ip[i] < '0' || ip[i] > '9') + throw std::runtime_error("Non-digit character found in ip"); + this_byte = (this_byte * 10) + (ip[i] - '0'); + i++; + } + if (this_byte > 0xFF) { + throw std::runtime_error("Byte greater than 255"); + } + result = (result << 8) | (this_byte & 0xFF); + bytes_found++; + if(bytes_found < 4 && i < ip.size() && ip[i] == '.') + i++; + } + if(bytes_found < 4 || (i < ip.size() && bytes_found == 4)) + throw std::runtime_error("Invalid ip address"); + return result; +} }