#include <stdio.h>
#include <curl/curl.h>


CURL *curl=NULL;

void printTCPInfo(CURL *curl)
{
    char* rip = NULL;
    char* lip = NULL;
    long rport = -1;
    long lport = -1;
    curl_easy_getinfo(curl, CURLINFO_PRIMARY_IP, &rip);
    curl_easy_getinfo(curl, CURLINFO_LOCAL_IP, &lip);
    curl_easy_getinfo(curl, CURLINFO_PRIMARY_PORT, &rport);
    curl_easy_getinfo(curl, CURLINFO_LOCAL_PORT, &lport);

    printf("lip:%s lport:%ld <---> rip:%s rport:%ld\n",lip?lip:"na", lport, rip?rip:"na", rport);
}


void performEasyRequest(const char* cUrl)
{

    CURLcode res;

    if (!curl)
    {
        curl = curl_easy_init();
        printf("curl handle init\n");
    }
    else
    {
        curl_easy_reset(curl);
    }

    if (curl)
    {
        printf("easy start----------------\n");
        printf("URL:%s\n",cUrl);

        char errorBuffer[CURL_ERROR_SIZE];
        errorBuffer[0] = '\0';

        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER , errorBuffer);


        curl_easy_setopt(curl, CURLOPT_URL, cUrl);
        res = curl_easy_perform(curl);
        printf("curl finished--------------------\n");

        printf("res:%d -> \"%s\" -> \"%s\" \n",res, curl_easy_strerror(res), errorBuffer);

        printTCPInfo(curl);
        printf("easy end--------------------\n");
    }
}


int main(int argc, char* argv[])
{
    const char* cUrl= "127.0.0.1";
    if ( argc>1 )
    {
        cUrl=argv[1];
    }

    performEasyRequest(cUrl);
    performEasyRequest(cUrl);

    return 0;
}

