티스토리 뷰

728x90
GetMyIPs C++ Code

GetMyIPs C++ Code

This code retrieves the IP addresses of the system's network interfaces on both Windows and Linux platforms using C++14.


#include <iostream>
#include <vector>
#include <string>

// Platform-specific includes
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#endif

std::vector<std::string> GetMyIPs() {
    std::vector<std::string> ipAddresses;

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

    char hostname[256];
    if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) {
        std::cerr << "gethostname failed." << std::endl;
        WSACleanup();
        return ipAddresses;
    }

    struct addrinfo hints = {};
    hints.ai_family = AF_INET; // IPv4
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    struct addrinfo* result = nullptr;
    if (getaddrinfo(hostname, nullptr, &hints, &result) != 0) {
        std::cerr << "getaddrinfo failed." << std::endl;
        WSACleanup();
        return ipAddresses;
    }

    for (struct addrinfo* ptr = result; ptr != nullptr; ptr = ptr->ai_next) {
        struct sockaddr_in* sockaddr_ipv4 = reinterpret_cast<struct sockaddr_in*>(ptr->ai_addr);
        char ip[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &sockaddr_ipv4->sin_addr, ip, sizeof(ip));
        ipAddresses.emplace_back(ip);
    }

    freeaddrinfo(result);
    WSACleanup();

#else
    struct ifaddrs* ifaddr;
    if (getifaddrs(&ifaddr) == -1) {
        perror("getifaddrs");
        return ipAddresses;
    }

    for (struct ifaddrs* ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr == nullptr) continue;
        if (ifa->ifa_addr->sa_family == AF_INET) { // IPv4 only
            char ip[INET_ADDRSTRLEN];
            struct sockaddr_in* sockaddr_ipv4 = reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr);
            inet_ntop(AF_INET, &sockaddr_ipv4->sin_addr, ip, sizeof(ip));
            ipAddresses.emplace_back(ip);
        }
    }

    freeifaddrs(ifaddr);
#endif

    return ipAddresses;
}

int main() {
    auto ips = GetMyIPs();

    std::cout << "IP Addresses:" << std::endl;
    for (const auto& ip : ips) {
        std::cout << " - " << ip << std::endl;
    }

    return 0;
}

    
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/12   »
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
글 보관함
250x250