在 C++ 中进行 FTP 开发(客户端或服务器),可以使用以下方案和开源库
1. C++ FTP 客户端库
(1) libcurl(推荐)
【链接】libcurl - your network transfer library
特点:
跨平台(Windows/Linux/macOS)
支持 FTP / FTPS(SSL/TLS) / HTTP / HTTPS
简单易用,API 稳定
示例代码(上传文件):
#include <curl/curl.h>
#include <fstream>
int main() {
CURL *curl = curl_easy_init();
if (curl) {
// 设置 FTP 服务器地址
curl_easy_setopt(curl, CURLOPT_URL, "ftp://example.com/upload/file.txt");
// 设置用户名和密码
curl_easy_setopt(curl, CURLOPT_USERPWD, "username:password");
// 上传本地文件
std::ifstream file("local_file.txt", std::ios::binary);
if (file) {
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl, CURLOPT_READDATA, &file);
// 执行 FTP 上传
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "FTP upload failed: %s\n", curl_easy_strerror(res));
}
}
curl_easy_cleanup(curl);
}
return 0;
}
编译方式(Linux):
g++ ftp_upload.cpp -lcurl -o ftp_upload
适用场景:
-
需要快速实现 FTP 文件传输
-
支持 SSL/TLS 加密(FTPS)
(2) Poco::Net(POCO C++)
【链接】https://github.com/pocoproject/poco
特点:
跨平台,C++ 标准风格
支持 FTP/HTTP/WebSocket 等协议
适用于更复杂的网络应用
示例代码(下载文件):
#include <Poco/Net/FTPClientSession.h>
#include <Poco/StreamCopier.h>
#include <fstream>
int main() {
Poco::Net::FTPClientSession ftp("ftp.example.com");
ftp.login("username", "password");
std::ofstream localFile("downloaded_file.txt", std::ios::binary);
std::istream& remoteFile = ftp.beginDownload("remote_file.txt");
Poco::StreamCopier::copyStream(remoteFile, localFile);
ftp.endDownload();
return 0;
}
编译方式(需安装 POCO 库):
g++ ftp_download.cpp -lPocoNet -lPocoFoundation -o ftp_download
适用场景:
-
需要更高级的 C++ 网络编程
-
支持 FTP 目录操作(
listDirectory
,setWorkingDirectory
)
2. C++ FTP 服务器库
(1) FineFTP-Server
【链接】https://github.com/eclipse-ecal/fineftp-server
特点:
轻量级、开源(MIT 协议)
支持 FTP/FTPS(SSL/TLS)
适用于 Windows
示例代码(启动 FTP 服务器):
#include "fineftp/server.h"
int main() {
fineftp::FtpServer server(2121); // 监听端口 2121
server.addUser("user", "password", "C:\\FTP_Share", fineftp::Permission::All);
server.start();
// 保持服务器运行
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
适用场景:
-
需要在 Windows 上快速搭建 FTP 服务器
-
支持多用户和权限管理
(2) vsftpd
特点:
Linux 下最安全的 FTP 服务器,C 语言
支持 SSL/TLS(FTPS)
高性能,适合生产环境
安装方式(Ubuntu):
sudo apt install vsftpd
sudo systemctl start vsftpd
适用场景:
-
企业级 Linux FTP 服务器
-
需要高安全性和稳定性
3. 其他方案
方案 | 适用场景 | 特点 |
---|---|---|
Boost.Beast (ASIO) | 自定义 FTP 协议 | 适用于底层开发 |
Qt Network (QFtp) | Qt 应用集成 | 旧版 Qt4,新版需自行实现 |
Winsock (Windows API) | 底层 Socket 编程 | 适合学习 FTP 协议 |
需求 | 推荐方案 |
---|---|
快速实现 FTP 客户端 | libcurl |
C++ 标准风格 FTP 客户端 | Poco::Net |
Windows FTP 服务器 | FineFTP-Server |
Linux FTP 服务器 | vsftpd |
自定义 FTP 协议 | Boost.Beast |