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 "netio/netio.h" 9 : 10 : #include "felix/felix_client_properties.h" 11 : 12 : #include "felix/felix_client_exception.hpp" 13 : #include "felix/felix_client_util.hpp" 14 : 15 : #include "clog.h" 16 : 17 : // Returns "" in case neither the IP nor the Interface was found. 18 419 : std::string get_value_from_getifaddrs(std::string key, bool return_ip) { 19 419 : struct ifaddrs *ifaddr, *ifa; 20 419 : char ip[NI_MAXHOST]; 21 : 22 419 : if (getifaddrs(&ifaddr) == -1) { 23 0 : clog_fatal("getifaddrs problem"); 24 0 : throw FelixClientException("felix-client-util:get_value_from_getifaddrs getifaddrs problem"); 25 : } 26 : 27 3771 : for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { 28 3771 : if (ifa->ifa_addr == NULL) 29 2514 : continue; 30 : 31 3771 : int status = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); 32 3771 : if (status != 0) { 33 2514 : continue; 34 : } 35 : 36 1257 : const char* host = netio_hostname(key.c_str()); 37 1257 : std::string protocol = netio_protocol(key.c_str()); 38 1257 : if (((strcmp(ip, host) == 0) || (strcmp(ifa->ifa_name, host) == 0)) && (ifa->ifa_addr->sa_family==AF_INET)) { 39 419 : clog_trace("Interface : <%s>", ifa->ifa_name); 40 419 : clog_trace("Address : <%s>", ip); 41 838 : std::string value = protocol + ":" + (return_ip ? ip : ifa->ifa_name); 42 419 : freeifaddrs(ifaddr); 43 419 : clog_trace("InterfaceOrAddress : <%s>", value.c_str()); 44 419 : return value; 45 419 : } 46 1257 : } 47 : 48 : // not found 49 0 : freeifaddrs(ifaddr); 50 0 : return ""; 51 : } 52 : 53 419 : std::string get_ip_from_interface(const std::string& interface) { 54 838 : return get_value_from_getifaddrs(interface, true); 55 : } 56 : 57 0 : std::string get_interface_from_ip(const std::string& ip) { 58 0 : return get_value_from_getifaddrs(ip, false); 59 : } 60 : 61 419 : unsigned get_log_level(const std::string& log_level) { 62 419 : if (log_level == "trace") return CLOG_TRACE; 63 417 : if (log_level == "debug") return CLOG_DEBUG; 64 395 : if (log_level == "info") return CLOG_INFO; 65 16 : if (log_level == "notice") return CLOG_INFO; // for backwards compatibility 66 16 : if (log_level == "warning") return CLOG_WARN; 67 2 : if (log_level == "error") return CLOG_ERROR; 68 2 : if (log_level == "fatal") return CLOG_FATAL; 69 : return CLOG_INFO; 70 : } 71 : 72 6434 : std::string netio_socket_state_name(enum netio_socket_state e) 73 : { 74 6434 : switch (e) 75 : { 76 50 : case DISCONNECTED: return "DISCONNECTED"; 77 0 : case CONNECTING: return "CONNECTING"; 78 6384 : case CONNECTED: return "CONNECTED"; 79 0 : default: return "Unknown netio_socket_state_name for: " + std::to_string(e); 80 : } 81 : }