Skip to content

Instantly share code, notes, and snippets.

@Tosainu
Last active August 19, 2016 18:04
Show Gist options
  • Save Tosainu/9ab86754684a6954d374 to your computer and use it in GitHub Desktop.
Save Tosainu/9ab86754684a6954d374 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <unordered_map>
extern "C" {
#include <arpa/inet.h>
#include <sys/socket.h>
#include <ifaddrs.h>
}
std::unordered_map<std::string, std::string> get_if_list() {
std::unordered_map<std::string, std::string> result;
ifaddrs* ifap;
getifaddrs(&ifap);
for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr->sa_family == AF_INET) {
auto sa = reinterpret_cast<sockaddr_in*>(ifa->ifa_addr);
result.insert({ifa->ifa_name, inet_ntoa(sa->sin_addr)});
}
}
freeifaddrs(ifap);
return result;
}
auto main() -> int {
const auto ifs = get_if_list();
for (auto&& i : ifs) {
std::cout << i.first << "\t" << i.second << std::endl;
}
}
#include <cstdlib>
#include <iostream>
extern "C" {
#include <winsock2.h>
#include <iphlpapi.h>
}
#pragma comment(lib, "iphlpapi.lib")
auto main() -> int {
IP_ADAPTER_INFO* adapter_info = nullptr;
ULONG buf_size = 0;
// Make an initial call to GetAdaptersInfo to get
// the necessary size into the buf_size variable
if (GetAdaptersInfo(nullptr, &buf_size) == ERROR_BUFFER_OVERFLOW) {
adapter_info = static_cast<IP_ADAPTER_INFO*>(std::malloc(buf_size));
}
if (GetAdaptersInfo(adapter_info, &buf_size) == NO_ERROR) {
for (auto adapter = adapter_info; adapter; adapter = adapter->Next) {
if (adapter->Type == MIB_IF_TYPE_ETHERNET || IF_TYPE_IEEE80211) {
std::cout << "Adapter Name:\t" << adapter->AdapterName << "\n"
<< "Adapter Desc:\t" << adapter->Description << "\n";
std::cout << "Adapter Addr:\t" << std::hex;
for (std::size_t i = 0; i < adapter->AddressLength; ++i) {
if (i == (adapter->AddressLength - 1)) {
std::cout << static_cast<int>(adapter->Address[i]) << "\n";
} else {
std::cout << static_cast<int>(adapter->Address[i]) << "-";
}
}
std::cout << "IP Addr:\t" << adapter->IpAddressList.IpAddress.String << "\n"
<< "IP Mask:\t" << adapter->IpAddressList.IpMask.String << "\n"
<< "Gateway:\t" << adapter->GatewayList.IpAddress.String << "\n";
}
std::cout << "--------------------------------" << std::endl;
}
}
std::free(adapter_info);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment