-
-
Notifications
You must be signed in to change notification settings - Fork 637
Expand file tree
/
Copy pathhostname_to_ip.cpp
More file actions
61 lines (53 loc) · 1.51 KB
/
Copy pathhostname_to_ip.cpp
File metadata and controls
61 lines (53 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include "hostname_to_ip.h"
#include "log.h"
#if defined(WINDOWS)
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#endif
namespace mavsdk {
std::optional<std::string> resolve_hostname_to_ip(const std::string& hostname)
{
#if defined(WINDOWS)
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed" << std::endl;
return {};
}
#endif
addrinfo hints{};
hints.ai_family = AF_INET; // IPv4
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
addrinfo* result = nullptr;
int res = getaddrinfo(hostname.c_str(), nullptr, &hints, &result);
if (res != 0) {
#if defined(WINDOWS)
LogErr() << "getaddrinfo failed: " << WSAGetLastError();
WSACleanup();
#else
LogErr() << "getaddrinfo failed: " << gai_strerror(res);
#endif
return {};
}
std::optional<std::string> ipAddress;
for (addrinfo* ptr = result; ptr != nullptr; ptr = ptr->ai_next) {
sockaddr_in* sockaddrIpv4 = reinterpret_cast<sockaddr_in*>(ptr->ai_addr);
char ipStr[INET_ADDRSTRLEN] = {};
if (inet_ntop(AF_INET, &(sockaddrIpv4->sin_addr), ipStr, INET_ADDRSTRLEN) != nullptr) {
ipAddress = ipStr;
break; // Take the first result
}
}
freeaddrinfo(result);
#if defined(WINDOWS)
WSACleanup();
#endif
return ipAddress;
}
} // namespace mavsdk