본문 바로가기
개발/C++

Convert IPv4 To IPv6

by -=HaeJuK=- 2024. 5. 21.
#include <iostream>
#include <string>
#ifdef _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #pragma comment(lib, "Ws2_32.lib")
#else
    #include <arpa/inet.h>
    #include <cstring>
#endif

bool convertIPv4ToIPv6(const std::string& ipv4AddrStr, std::string& ipv6AddrStr) {
    struct in_addr ipv4Addr;
    struct in6_addr ipv6Addr;

    // Convert the string IPv4 address to in_addr
    if (inet_pton(AF_INET, ipv4AddrStr.c_str(), &ipv4Addr) != 1) {
        std::cerr << "Invalid IPv4 address" << std::endl;
        return false;
    }

    // Initialize the IPv6 address to zero
    std::memset(&ipv6Addr, 0, sizeof(ipv6Addr));

    // Set the IPv4-mapped IPv6 prefix
    ipv6Addr.s6_addr[10] = 0xFF;
    ipv6Addr.s6_addr[11] = 0xFF;

    // Copy the IPv4 address into the last 4 bytes of the IPv6 address
    std::memcpy(&ipv6Addr.s6_addr[12], &ipv4Addr, sizeof(ipv4Addr));

    char ipv6AddrStrBuf[INET6_ADDRSTRLEN];
    // Convert the in6_addr to a string
    if (inet_ntop(AF_INET6, &ipv6Addr, ipv6AddrStrBuf, INET6_ADDRSTRLEN) == nullptr) {
        std::cerr << "Failed to convert IPv6 address to string" << std::endl;
        return false;
    }

    ipv6AddrStr = ipv6AddrStrBuf;
    return true;
}

int main() {
#ifdef _WIN32
    // Initialize Winsock
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cerr << "WSAStartup failed" << std::endl;
        return 1;
    }
#endif

    std::string ipv4AddrStr = "192.168.1.1";
    std::string ipv6AddrStr;

    if (convertIPv4ToIPv6(ipv4AddrStr, ipv6AddrStr)) {
        std::cout << "IPv6-mapped IPv4 address: " << ipv6AddrStr << std::endl;
    } else {
        std::cerr << "Failed to convert IPv4 address to IPv6-mapped IPv4 address" << std::endl;
#ifdef _WIN32
        WSACleanup();
#endif
        return 1;
    }

#ifdef _WIN32
    WSACleanup();
#endif

    return 0;
}
반응형