Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.3 kB
1
Indexable
Never
#include <iostream>
#include <string>
#include <vector>
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdexcept>

#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")

std::string get_ip_address_from_mac(const std::string& mac_address) {
    // Allocate memory for the IP net table
    DWORD buffer_size = 0;
    PMIB_IPNETTABLE ip_net_table = nullptr;

    // Retrieve the required buffer size
    DWORD result = GetIpNetTable(ip_net_table, &buffer_size, FALSE);
    if (result != ERROR_INSUFFICIENT_BUFFER) {
        throw std::runtime_error("Failed to get buffer size for IP net table.");
    }

    // Allocate the memory and retrieve the IP net table
    ip_net_table = reinterpret_cast<PMIB_IPNETTABLE>(new char[buffer_size]);
    result = GetIpNetTable(ip_net_table, &buffer_size, FALSE);
    if (result != NO_ERROR) {
        delete[] ip_net_table;
        throw std::runtime_error("Failed to get IP net table: " + std::to_string(result));
    }

    // Search for the MAC address in the IP net table
    std::string ip_address;
    for (DWORD i = 0; i < ip_net_table->dwNumEntries; i++) {
        MIB_IPNETROW& row = ip_net_table->table[i];

        char mac_buffer[18];
        snprintf(mac_buffer, sizeof(mac_buffer), "%02X-%02X-%02X-%02X-%02X-%02X",
                 row.bPhysAddr[0], row.bPhysAddr[1],
                 row.bPhysAddr[2], row.bPhysAddr[3],
                 row.bPhysAddr[4], row.bPhysAddr[5]);

        if (mac_address == mac_buffer) {
            char ip_buffer[INET_ADDRSTRLEN];
            InetNtop(AF_INET, &row.dwAddr, ip_buffer, INET_ADDRSTRLEN);
            ip_address = ip_buffer;
            break;
        }
    }

    delete[] ip_net_table;

    if (ip_address.empty()) {
        throw std::runtime_error("IP address not found for MAC address: " + mac_address);
    }

    return ip_address;
}

int main() {
    try {
        std::string mac_address = "AA-BB-CC-DD-EE-FF"; // Replace with the MAC address you want to look up
        std::string ip_address = get_ip_address_from_mac(mac_address);
        std::cout << "IP address for MAC " << mac_address << ": " << ip_address << std::endl;
    } catch (const std::runtime_error& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}