1
0
mirror of https://github.com/mfontanini/libtins synced 2026-01-28 20:44:26 +01:00

Fixed HWAddress and IPv4Address' constructors from const char*.

This commit is contained in:
Matias Fontanini
2012-08-10 00:22:15 -03:00
parent 55be59ee15
commit e3ca2fd978
3 changed files with 42 additions and 4 deletions

View File

@@ -51,7 +51,8 @@ public:
convert(address, buffer);
}
HWAddress(const char *address) {
template<size_t i>
HWAddress(const char (&address)[i]) {
convert(address, buffer);
}
@@ -105,6 +106,11 @@ public:
);
return os << to_string(addr.buffer[HWAddress::address_size-1]);
}
template<typename OutputIterator>
OutputIterator copy(OutputIterator iter) {
return std::copy(begin(), end(), iter);
}
private:
template<typename OutputIterator>
static void convert(const std::string &hw_addr, OutputIterator output);

View File

@@ -31,7 +31,12 @@ namespace Tins {
public:
IPv4Address(uint32_t ip = 0);
IPv4Address(const std::string &ip);
IPv4Address(const char *ip);
template<size_t n>
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;
};
};

View File

@@ -19,6 +19,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdexcept>
#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;
}
}