diff --git a/influxdb.hpp b/influxdb.hpp index 15fa3d7..089cd23 100644 --- a/influxdb.hpp +++ b/influxdb.hpp @@ -9,6 +9,7 @@ #include #include #include +#include #ifdef _WIN32 #define NOMINMAX @@ -26,6 +27,7 @@ #include #include #include + #include #include #define closesocket close #endif @@ -37,8 +39,26 @@ namespace influxdb_cpp { std::string db_; std::string usr_; std::string pwd_; - server_info(const std::string& host, int port, const std::string& db = "", const std::string& usr = "", const std::string& pwd = "") - : host_(host), port_(port), db_(db), usr_(usr), pwd_(pwd) {} + server_info(const std::string& host, int port, const std::string& db = "", const std::string& usr = "", const std::string& pwd = "") { + port_ = port; + db_ = db; + usr_ = usr; + pwd_ = pwd; + + //convert hostname to ip-address + hostent * record = gethostbyname(host.c_str()); + if(record == NULL) + { + printf("Cannot resolve IP address from hostname: %s is unavailable. Try to ping the host.\n", host.c_str()); + std::exit(-1); + } + in_addr * address = (in_addr * )record->h_addr; + std::string ip_address = inet_ntoa(* address); + + printf("Resolved IP address from hostname: %s.\n", ip_address.c_str()); + + host_ = ip_address; + } }; namespace detail { struct meas_caller; @@ -200,6 +220,7 @@ namespace influxdb_cpp { addr.sin_family = AF_INET; addr.sin_port = htons(si.port_); + if((addr.sin_addr.s_addr = inet_addr(si.host_.c_str())) == INADDR_NONE) return -1; if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) return -2; diff --git a/test/main.cpp b/test/main.cpp index 8dd9a00..4607838 100644 --- a/test/main.cpp +++ b/test/main.cpp @@ -35,11 +35,16 @@ int main(int argc, char const *argv[]) cout << ret << endl; // query from table - influxdb_cpp::server_info si_new("127.0.0.1", 8086, "", "test", "test"); influxdb_cpp::query(resp, "show databases", si); cout << resp << endl; + // query from table, but use hostname instead of IP + influxdb_cpp::server_info si_hostname("localhost", 8086, "testx", "test", "test"); + influxdb_cpp::query(resp, "show databases", si_hostname); + cout << resp << endl; + // create_db + influxdb_cpp::server_info si_new("127.0.0.1", 8086, "", "test", "test"); influxdb_cpp::create_db(resp, "x", si_new); cout << resp << endl; return 0;