Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.8 kB
2
Indexable
Never
#include <iostream>
#include <string>
#include <winsock2.h>
#include <ws2ipdef.h>
#include <iphlpapi.h>
#include <stdexcept>

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

std::string get_mac_address_from_ip(const std::string& ip) {
    // Initialize Winsock
    WSADATA wsa_data;
    int wsa_result = WSAStartup(MAKEWORD(2, 2), &wsa_data);
    if (wsa_result != 0) {
        throw std::runtime_error("WSAStartup failed: " + std::to_string(wsa_result));
    }

    // Detect the IP address family (IPv4 or IPv6)
    SOCKADDR_STORAGE addr_storage;
    int addr_length = sizeof(addr_storage);
    int family = WSAStringToAddress(const_cast<char*>(ip.c_str()), AF_UNSPEC, NULL,
                                     reinterpret_cast<LPSOCKADDR>(&addr_storage), &addr_length);

    if (family == SOCKET_ERROR) {
        WSACleanup();
        throw std::runtime_error("Invalid IP address: " + ip);
    }

    // Convert the IP address string to a SOCKADDR_INET structure
    SOCKADDR_INET ip_address;
    ZeroMemory(&ip_address, sizeof(ip_address));
    ip_address.Ipv6.sin6_family = addr_storage.ss_family;

    if (addr_storage.ss_family == AF_INET) {
        InetPton(AF_INET, ip.c_str(), &ip_address.Ipv4.sin_addr);
    } else if (addr_storage.ss_family == AF_INET6) {
        InetPton(AF_INET6, ip.c_str(), &ip_address.Ipv6.sin6_addr);
    } else {
        WSACleanup();
        throw std::runtime_error("Unsupported address family");
    }

    // Resolve the IP address to a MAC address using ResolveIpNetEntry2
    MIB_IPNET_ROW2 ip_net_entry;
    ZeroMemory(&ip_net_entry, sizeof(ip_net_entry));
    ip_net_entry.InterfaceLuid.Value = 0; // Use the best available interface
    ip_net_entry.Address = ip_address;

    DWORD result = ResolveIpNetEntry2(&ip_net_entry, NULL);
    if (result != NO_ERROR) {
        WSACleanup();
        throw std::runtime_error("ResolveIpNetEntry2 failed: " + std::to_string(result));
    }

    // Format the MAC address as a string
    std::string mac_address;
    char mac_buffer[18];
    snprintf(mac_buffer, sizeof(mac_buffer), "%02X-%02X-%02X-%02X-%02X-%02X",
             ip_net_entry.PhysicalAddress[0], ip_net_entry.PhysicalAddress[1],
             ip_net_entry.PhysicalAddress[2], ip_net_entry.PhysicalAddress[3],
             ip_net_entry.PhysicalAddress[4], ip_net_entry.PhysicalAddress[5]);
    mac_address = mac_buffer;

    // Clean up Winsock
    WSACleanup();

    return mac_address;
}

int main() {
    try {
        std::string ip_address = "192.168.1.1"; // Replace with an IPv4 or IPv6 address
        std::string mac_address = get_mac_address_from_ip(ip_address);
        std::cout << "MAC address for IP " << ip_address << ": " << mac_address << std::endl;
    } catch (const std::runtime_error& e