49 lines
1.2 KiB
C++
49 lines
1.2 KiB
C++
#ifndef COMPLIB_SERVER_NETWORKUTILS_H
|
|
#define COMPLIB_SERVER_NETWORKUTILS_H
|
|
|
|
#include <unistd.h>
|
|
#include <string>
|
|
#include <netdb.h>
|
|
#include "spdlog/spdlog.h"
|
|
|
|
#include <sys/types.h>
|
|
#include <ifaddrs.h>
|
|
|
|
namespace networkUtils {
|
|
inline std::tuple<std::string, std::string> get_current_host_and_ip() {
|
|
struct ifaddrs *ifaddr, *ifa;
|
|
int family, s;
|
|
char host[NI_MAXHOST];
|
|
|
|
if (getifaddrs(&ifaddr) == -1) {
|
|
spdlog::error("getifaddrs failed");
|
|
freeifaddrs(ifaddr);
|
|
return std::tuple("", "");
|
|
}
|
|
|
|
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
|
|
if (ifa->ifa_addr == NULL)
|
|
continue;
|
|
|
|
family = ifa->ifa_addr->sa_family;
|
|
|
|
if (family == AF_INET) {
|
|
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
|
|
if (s != 0) {
|
|
spdlog::error("getnameinfo() failed: {}", gai_strerror(s));
|
|
freeifaddrs(ifaddr);
|
|
return std::tuple("", "");
|
|
}
|
|
|
|
if (std::string(ifa->ifa_name) != "lo") {
|
|
freeifaddrs(ifaddr);
|
|
return std::tuple(ifa->ifa_name, std::string(host));
|
|
}
|
|
}
|
|
}
|
|
|
|
return std::tuple("", "");
|
|
}
|
|
}
|
|
|
|
#endif //COMPLIB_SERVER_NETWORKUTILS_H
|