This repository has been archived on 2025-06-01. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
compLIB/server_v2/include/networkUtils.hpp
Konstantin Lampalzer 1d91792c56 Update
2022-10-05 23:13:40 +02:00

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