天天看點

libcurl庫 ftp上傳檔案到伺服器

libcurl主要功能就是用不同的協定連接配接和溝通不同的伺服器。libcurl目前支援http, https, ftp, gopher, telnet, dict, file, 和ldap 協定。

今天主要是記錄項目中libcurl ftp的使用,關于libcurl的API描述,這個連結已經描述的很詳細了:https://curl.haxx.se/libcurl/c/allfuncs.html

以下代碼在項目中學習到的,畢竟是小白隻能修修補補,二手碼農

用例如下:

/*****************************************************************************
 函 數 名  : pkt_ftp_send
 功能描述  : ftp發送檔案
 輸入參數  : char *user    ftp伺服器使用者名            
             char *passwd  ftp伺服器密碼            
             char*dir      發送檔案所在目錄,注意目錄後有"/",如 "/tmp/path/"            
             char *file     待發送檔案名           
 輸出參數  : 無
 返 回 值  : 
 調用函數  : 
 被調函數  : 
 
 修改曆史      :
  1.日    期   : xxxx
    作    者   : xxx
    修改内容   : 新生成函數

*****************************************************************************/
INT32 pkt_ftp_send(char *user, char *passwd,  char*dir, char *file)
{
    CURLcode result;
    long ulFileSize;
    FILE*fp = NULL;
    char acUserPwd[128] = "";
    char acFtpForm[256] = "";
    struct in_addr stIp; 
    char acIp[32];
    UINT16 usPort;
    char fileName[256] = "";

    /* 擷取伺服器IP&PORT */
    stIp.s_addr = 0xc0a801f9;       /* 預設伺服器IP位址 192.168.1.249 */ 
    if(inet_ntop(AF_INET, (void *)&stIp, acIp, (socklen_t )sizeof(acIp)) == 0) {
        return;
    }
    
    usPort = 2121; 
    
    /* 讀取檔案 */
    snprintf(fileName, sizeof(fileName),"%s%s", dir, file);
    fp = fopen(fileName, "r");
    if(NULL == fp)
    { 
        return -1;
    }
    fseek(fp, 0L, SEEK_END);
    ulFileSize = ftell(fp);
    fseek(fp, 0L, SEEK_SET);

    /* 初始化CURL指針 */
    CURL* curl = curl_easy_init();
    if(NULL == curl)
    {
        fclose(fp);
        return -1;
    }  
    
    snprintf(acUserPwd, 128, "%s:%s", user, passwd);
    snprintf(acFtpForm, 128, "ftp://%s:%u/%s", acIp, usPort, file);

    curl_easy_setopt(curl, CURLOPT_USERPWD, acUserPwd);
    curl_easy_setopt(curl, CURLOPT_URL, acFtpForm);
    curl_easy_setopt(curl, CURLOPT_READDATA, fp);
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
    curl_easy_setopt(curl, CURLOPT_INFILESIZE, ulFileSize);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
       
    result = curl_easy_perform(curl);
    if(CURLE_OK!=result)
    {   
        curl_easy_cleanup(curl);
        fclose(fp);
        return -1;
    } 
    curl_easy_cleanup(curl);  
    fclose(fp);

    return 0; 
}