cleaning and new functions

This commit is contained in:
Erik Frojdh
2019-04-01 10:36:47 +02:00
parent 05709e2f47
commit 959d9aa5d1
6 changed files with 62 additions and 69 deletions

View File

@ -17,7 +17,7 @@
#endif
#ifndef FILELOG_MAX_LEVEL
#define FILELOG_MAX_LEVEL logINFO
#define FILELOG_MAX_LEVEL logDEBUG1
#endif

View File

@ -6,9 +6,11 @@ namespace sls {
std::string MacAddrToString(uint64_t mac);
uint64_t MacStringToUint(std::string mac);
uint32_t IpStringToUint(const char* ipstr);
std::string IpToString(uint32_t ip);
uint32_t IpStringToUint(const char *ipstr);
uint32_t HostnameToIp(const char *const hostname);
std::string IpToString(uint32_t ip);
std::string IpToHexString(uint32_t ip);
uint32_t HostnameToIp(const char *hostname);
} // namespace sls

View File

@ -39,15 +39,21 @@ uint32_t IpStringToUint(const char *ipstr) {
}
std::string IpToString(uint32_t ip) {
char ipstring[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, &ip, ipstring, INET_ADDRSTRLEN) == nullptr) {
// handle error
}
// TODO! Check return
char ipstring[INET_ADDRSTRLEN]{};
inet_ntop(AF_INET, &ip, ipstring, INET_ADDRSTRLEN);
return ipstring;
}
uint32_t HostnameToIp(const char *const hostname) {
std::string IpToHexString(uint32_t ip){
std::ostringstream ss;
ss << std::hex << std::setfill('0') << std::setw(2);
for (int i=0; i!=4; ++i){
ss << ((ip >> i*8) & 0xFF);
}
return ss.str();
}
uint32_t HostnameToIp(const char *hostname) {
struct addrinfo hints, *result;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
@ -61,6 +67,8 @@ uint32_t HostnameToIp(const char *const hostname) {
return ip;
}
} // namespace sls
// char ipstring[INET_ADDRSTRLEN];

View File

@ -21,11 +21,11 @@ TEST_CASE("Convert mac address") {
}
}
TEST_CASE("Convert IP"){
TEST_CASE("Convert IP") {
std::vector<uint32_t> vec_addr{4073554305, 2747957633, 2697625985};
std::vector<std::string> vec_ans{"129.129.205.242", "129.129.202.163", "129.129.202.160"};
for (int i=0; i!= vec_addr.size(); ++i){
for (int i = 0; i != vec_addr.size(); ++i) {
auto ip = vec_addr[i];
auto answer = vec_ans[i];
@ -35,10 +35,19 @@ TEST_CASE("Convert IP"){
}
}
TEST_CASE("IP not valid"){
TEST_CASE("IP not valid") {
CHECK(IpStringToUint("hej") == 0);
CHECK(IpStringToUint("mpc2408") == 0);
}
TEST_CASE("Convert ip to hex") {
std::vector<std::string> ipstrings{"74.125.43.99", "129.129.202.217"};
std::vector<std::string> vec_ans{"4a7d2b63", "8181cad9"};
for (int i = 0; i != ipstrings.size(); ++i) {
uint32_t ip = IpStringToUint(ipstrings[i].c_str());
CHECK(IpToHexString(ip) == vec_ans[i]);
}
}
// TEST_CASE("Lookup ip")