Search code examples
ccurlftplibcurlconnectivity

How to check FTP connectivity using CURL library in c?


I want to check FTP server connectivity using curl library in c program. Can anyone tell me how to do that without using any data transfer means i don't want to transfer any file to check that. I want is like CURLOPT_CONNECT_ONLY option which is available for only HTTP, SMTP and POP3 protocols not for FTP.

Curl version : 7.24 Requirement : FTP server connectivity test.


Solution

  • Here in below example, Only connect request will be delivered to FTP server and if server is pingable then it will give CURLE_OK return code other wise give failure response after specific timeout(60 sec). Other options you can set as per your requirement from http://curl.haxx.se/libcurl/c/ .

    ...
    snprintf(ftp_url, BUF_LEN_512, "ftp://%s:%s@%s", uploadConf->username, uploadConf->password, uploadConf->ip);
    
    // Reset curl lib
    curl_easy_reset(curl);
    
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, throw_away);
    if (CURLE_OK != (res = curl_easy_setopt(curl, CURLOPT_URL, ftp_url)))
    {
        printf("Failed to check ftp url, Error : %s : %d\n", curl_easy_strerror(res), res);
    }
    curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
    
    // Connection establishment timeout
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 60);
    
    if (CURLE_OK != (res = curl_easy_perform(curl)))
    {
        /* If fail to connect */
    }
    else
    {
        /* If connected succesfully */
    }
    
    
    static size_t throw_away(void *ptr, size_t size, size_t nmemb, void *data)
    {
        size_t res;
    
        res = (size_t)(size * nmemb);
    
        /* we are not interested in the headers itself, so we only return the size we would have saved ... */
        return res;
    }
    

    Hope it will help you all to test connectivity to FTP server using libcurl in c.