Line data Source code
1 : #include <sys/socket.h> 2 : #include <sys/types.h> 3 : #include <netdb.h> 4 : #include <ifaddrs.h> 5 : #include <cstring> 6 : #include <list> 7 : 8 : #include "felix/felix_client_properties.h" 9 : 10 : #include "felix/felix_client_exception.hpp" 11 : #include "felix/felix_client_util.hpp" 12 : 13 : #include "clog.h" 14 : 15 : // Returns "" in case neither the IP nor the Interface was found. 16 673 : std::string get_value_from_getifaddrs(std::string key, bool return_ip) { 17 673 : struct ifaddrs *ifaddr, *ifa; 18 673 : char ip[NI_MAXHOST]; 19 : 20 673 : if (getifaddrs(&ifaddr) == -1) { 21 0 : clog_fatal("getifaddrs problem"); 22 0 : throw FelixClientException("felix-client-util:get_value_from_getifaddrs getifaddrs problem"); 23 : } 24 : 25 5384 : for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { 26 5384 : if (ifa->ifa_addr == NULL) 27 0 : continue; 28 : 29 5384 : int status = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); 30 5384 : if (status != 0) { 31 3365 : continue; 32 : } 33 : 34 2019 : if (((strcmp(ip, key.c_str()) == 0) || (strcmp(ifa->ifa_name, key.c_str()) == 0)) && (ifa->ifa_addr->sa_family==AF_INET)) { 35 673 : clog_trace("Interface : <%s>", ifa->ifa_name); 36 673 : clog_trace("Address : <%s>", ip); 37 673 : std::string value = return_ip ? ip : ifa->ifa_name; 38 673 : freeifaddrs(ifaddr); 39 673 : return value; 40 673 : } 41 : } 42 : 43 : // not found 44 0 : freeifaddrs(ifaddr); 45 0 : return ""; 46 : } 47 : 48 673 : std::string get_ip_from_interface(const std::string& interface) { 49 1346 : return get_value_from_getifaddrs(interface, true); 50 : } 51 : 52 0 : std::string get_interface_from_ip(const std::string& ip) { 53 0 : return get_value_from_getifaddrs(ip, false); 54 : } 55 : 56 683 : unsigned get_log_level(const std::string& log_level) { 57 683 : if (log_level == "trace") return CLOG_TRACE; 58 677 : if (log_level == "debug") return CLOG_DEBUG; 59 641 : if (log_level == "info") return CLOG_INFO; 60 2 : if (log_level == "notice") return CLOG_INFO; // for backwards compatibility 61 2 : if (log_level == "warning") return CLOG_WARN; 62 2 : if (log_level == "error") return CLOG_ERROR; 63 2 : if (log_level == "fatal") return CLOG_FATAL; 64 : return CLOG_INFO; 65 : } 66 : 67 2836 : std::string netio_socket_state_name(enum netio_socket_state e) 68 : { 69 2836 : switch (e) 70 : { 71 112 : case DISCONNECTED: return "DISCONNECTED"; 72 0 : case CONNECTING: return "CONNECTING"; 73 2724 : case CONNECTED: return "CONNECTED"; 74 0 : default: return "Unknown netio_socket_state_name for: " + std::to_string(e); 75 : } 76 : }