티스토리 뷰

개발/C,C++

Get Public IP in C++

-=HaeJuK=- 2024. 12. 2. 15:01
728x90
Get Public IP in C++

Get Public IP in C++

This code uses libcurl to retrieve the public IP address by making an HTTP request to http://api.ipify.org.


#include <iostream>
#include <string>
#include <curl/curl.h>

size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) {
    userp->append((char*)contents, size * nmemb);
    return size * nmemb;
}

std::string GetPublicIP() {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://api.ipify.org");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);

        if (res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
            return "";
        }
    }

    return readBuffer;
}

int main() {
    std::string publicIP = GetPublicIP();
    if (!publicIP.empty()) {
        std::cout << "Public IP: " << publicIP << std::endl;
    } else {
        std::cerr << "Failed to retrieve public IP." << std::endl;
    }

    return 0;
}

    

Instructions

  • Install libcurl:
    • Windows: Download from curl.se.
    • Linux: Run sudo apt install libcurl4-openssl-dev.
  • Compile the code:
  • g++ -o GetPublicIP GetPublicIP.cpp -lcurl
  • Run the compiled executable:
  • ./GetPublicIP
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
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