#include #include #include #include #include #include #include "MKLib.h" using namespace std; MacAddr::MacAddr() { for(char i = 0; i < MAC_ADDR_BYTES; i++) { this->addr.addr[i] = 0; } } MacAddr::MacAddr(uint8_t *arr) { for(char i = 0; i < MAC_ADDR_BYTES; i++) { this->addr.addr[i] = arr[i]; } } bool MacAddr::operator<(const MacAddr &rhs) const { int diff = 0, i = 0; while(diff == 0 && i < MAC_ADDR_BYTES) { diff = this->addr.addr[i] - rhs.addr.addr[i++]; } return diff < 0; } bool MacAddr::operator==(const MacAddr &rhs) const { int diff = 0, i = 0; while(diff == 0 && i < MAC_ADDR_BYTES) { diff = this->addr.addr[i] - rhs.addr.addr[i++]; } return diff == 0; } string MKLib::ip2string(ip4_t addr) { string str; in_addr inAddr = {addr}; str = inet_ntoa(inAddr); return str; } string MKLib::mac2string(mac_t mac) { return FString("%02x:%02x:%02x:%02x:%02x:%02x", mac.addr[0], mac.addr[1], mac.addr[2], mac.addr[3], mac.addr[4], mac.addr[5]); } ip4_t MKLib::parseIP4Addr(const char *addr) { // ip4_t ip = inet_addr(addr); // this does not catch bad strings ip4_t ip = 0; int val, sections = 0; char buf[kIP4MaxLen + 2] = {'\0'}; char *tAddr = buf, *part, *validate; if(addr == NULL) { throw BaseException("NULL IPv4 address"); } strncpy(tAddr, addr, kIP4MaxLen + 1); while(part = strtok(tAddr, ".")) { errno = 0; val = strtol(part, &validate, 10); if(errno || *validate != '\0' || val < 0 || val > 255) { errno = 0; throw BaseException("Invalid IPv4 address"); } ip = (ip << 8) | val; tAddr = NULL; sections++; } if(sections != 4) { throw BaseException("Invalid IPv4 address"); } return htonl(ip); } mac_t MKLib::parseMACAddr(const char *addr){ mac_t r_mac = {0}; // zeros the whole array int val, sections = 0; char buf[kMACMaxLen + 2] = {'\0'}; char *tAddr = buf, *part, *validate; if(addr == NULL) { throw BaseException("Invalid MAC, is NULL"); } strncpy(tAddr, addr, kMACMaxLen + 1); while(part = strtok(tAddr, ":")) { if(sections >= MAC_ADDR_BYTES) { throw BaseException(FString("Invalid MAC, too long: %s", addr)); } errno = 0; val = strtol(part, &validate, 16); if(errno || *validate != '\0' || val < 0 || val > 255) { errno = 0; throw BaseException(FString("Invalid MAC, illegal value: %s", addr)); } r_mac.addr[sections] = val; tAddr = NULL; sections++; } if(sections != MAC_ADDR_BYTES) { throw BaseException(FString("Invalid MAC, too short: %s", addr)); } return r_mac; } FString::FString(char *fmt, ...) { static const int bufLen = 1024; static char buf[bufLen]; va_list args; va_start(args, fmt); vsnprintf(buf, bufLen, fmt, args); va_end(args); *(std::string *)this = std::string(buf); }