Examples › Socket Examples
socket_ftp_client
C++20 or laterDataReel 6.4.3Portable C++ (tested on Linux)
Legacy: examples_socket/ftp_client/testprog.cpp · Modern: examples_modern/socket/ftp_client/modern.cpp
Modern equivalent of the FTP client example. gxsFTPClient stays. The directory listing goes into a std::string buffer and is split into a std::vector<std::string> of names with std::string_view; the steps report errors through one lambda. With no arguments a scripted server on 127.0.0.1 (with a passive mode data connection) answers; with "SERVER USER PASSWORD" it uses a real server (FTP sends the password in the clear: test servers only).
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| Atoi(), Atol(), Atof(), atoi() | std::from_chars() into std::optional<T>; std::stoi() | C++17 | Overflow and junk are reported, not turned into 0. |
| DiskFileB | std::fstream (read, write, seekg/seekp, tellg) | C++98 | |
| gxsHTTPClient, gxsSMTPClient, gxsPOP3Client, gxsIMAPClient, gxsFTPClient, gxsTelnetClient | keep them; std::string buffers; reply parsing with std::string_view and std::from_chars | C++17 |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_socket/ftp_client/testprog.cpp 340 lines
#include "gxdlcode.h" #if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library #include <iostream> using namespace std; // Use unqualified names for Standard C++ library #else // Use the old iostream library by default #include <iostream.h> #endif // __USE_ANSI_CPP__ #include <stdlib.h> #include "gxsftp.h" #ifdef __MSVC_DEBUG__ #include "leaktest.h" #endif int CheckError(gxsFTPClient *ftp, int close_on_err = 1) { if(ftp->GetSocketError() != gxSOCKET_NO_ERROR) { cout << ftp->SocketExceptionMessage() << "\n" << flush; if(ftp->reply_buf[0] != 0) { // Check the reply buffer cout << ftp->reply_buf << flush; } if(close_on_err == 1) { ftp->Close(); } return 0; } return 1; // No errors reported } void ClearInputStream(istream &s) // Used to clear istream { char c; s.clear(); while(s.get(c) && c != '\n') { ; } } void Menu() { cout << "\n" << flush; cout << "(a) Set image type to ASCII" << "\n" << flush; cout << "(A) Set active mode on (default)" << "\n" << flush; cout << "(b, B) Set image type to binary" << "\n" << flush; cout << "(c, C) Change working directory" << "\n" << flush; cout << "(d, D) Delete a file" << "\n" << flush; cout << "(h, H, ?) Display this menu" << "\n" << flush; cout << "(g, G) Get a file" << "\n" << flush; cout << "(l) Long directory listing" << "\n" << flush; cout << "(L) Short directory listing" << "\n" << flush; cout << "(M, m) Make a directory" << "\n" << flush; cout << "(n) Long named directory listing" << "\n" << flush; cout << "(N) Short named directory listing" << "\n" << flush; cout << "(p) Put a file" << "\n" << flush; cout << "(P) Set passive FTP mode on" << "\n" << flush; cout << "(q, Q) Quit this program" << "\n" << flush; cout << "(r, R) Remove directory" << "\n" << flush; cout << "(s, S) Display statistics" << "\n" << flush; cout << "(v, V) Move a file" << "\n" << flush; cout << "(w, W) Get working directory" << "\n" << flush; cout << "(z, Z) Get a file size in bytes" << "\n" << flush; cout << "\n" << flush; } void List(gxsFTPClient *ftp, int full) { const int sbuf_size = 8192; char sbuf[sbuf_size]; sbuf[0] = 0; ftp->FTPList(sbuf, sizeof(sbuf), full); if(!CheckError(ftp, 0)) return; cout << sbuf << flush << "\n" << flush; cout << ftp->reply_buf << flush; } void ListDir(gxsFTPClient *ftp, int full) { char name[255]; cout << "Enter file or directory name>"; cin.width(sizeof(name)); // 10/31/2026: No overflow of name cin >> name; const int sbuf_size = 8192; char sbuf[sbuf_size]; sbuf[0] = 0; ftp->FTPList(sbuf, sizeof(sbuf), full, name); if(!CheckError(ftp, 0)) return; cout << sbuf << flush << "\n" << flush; cout << ftp->reply_buf << flush; } void Stat(gxsFTPClient *ftp) { ftp->FTPStat(); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void PWD(gxsFTPClient *ftp) { ftp->FTPPWD(); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void ASC(gxsFTPClient *ftp) { ftp->FTPImageType('A'); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void Active(gxsFTPClient *ftp) { ftp->FTPActive(); cout << "Passive mode off" << "\n" << flush; } void Passive(gxsFTPClient *ftp) { ftp->FTPPassive(); cout << "Passive mode on" << "\n" << flush; } void BIN(gxsFTPClient *ftp) { ftp->FTPImageType('B'); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void ChDir(gxsFTPClient *ftp) { char sbuf[255]; cout << "Enter directory name>"; cin.width(sizeof(sbuf)); // 10/31/2026: No overflow of sbuf cin >> sbuf; ftp->FTPChDir((const char *)sbuf); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void MkDir(gxsFTPClient *ftp) { char sbuf[255]; cout << "Enter directory to make>"; cin.width(sizeof(sbuf)); // 10/31/2026: No overflow of sbuf cin >> sbuf; ftp->FTPMkDir((const char *)sbuf); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void RmDir(gxsFTPClient *ftp) { char sbuf[255]; cout << "Enter directory to remove>"; cin.width(sizeof(sbuf)); // 10/31/2026: No overflow of sbuf cin >> sbuf; ftp->FTPRmDir((const char *)sbuf); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void Delete(gxsFTPClient *ftp) { char sbuf[255]; cout << "Enter file name to delete>"; cin.width(sizeof(sbuf)); // 10/31/2026: No overflow of sbuf cin >> sbuf; ftp->FTPDelete((const char *)sbuf); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void Move(gxsFTPClient *ftp) { char from[255]; char to[255]; cout << "Enter file name to rename>"; cin.width(sizeof(from)); // 10/31/2026: No overflow of from cin >> from; cout << "Enter new name>"; cin.width(sizeof(to)); // 10/31/2026: No overflow of to cin >> to; ftp->FTPMove((const char *)from, (const char *)to); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void Size(gxsFTPClient *ftp) { char sbuf[255]; cout << "Enter file name>"; cin.width(sizeof(sbuf)); // 10/31/2026: No overflow of sbuf cin >> sbuf; ftp->FTPSize((const char *)sbuf); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; } void Get(gxsFTPClient *ftp) { char rfile[255]; char lfile[255]; cout << "Enter file name to download>"; cin.width(sizeof(rfile)); // 10/31/2026: No overflow of rfile cin >> rfile; cout << "Enter local file name>"; cin.width(sizeof(lfile)); // 10/31/2026: No overflow of lfile cin >> lfile; // Open the output and truncate if it already exists DiskFileB stream(lfile, DiskFileB::df_READWRITE, DiskFileB::df_CREATE); if(!stream) { cout << "Could not open the " << lfile << " output file" << "\n" << flush; return; } FAU_t bytes; ftp->FTPGet((const char *)rfile, stream, bytes); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; cout << (long)bytes << " bytes transferred" << "\n" << flush; } void Put(gxsFTPClient *ftp) { char rfile[255]; char lfile[255]; cout << "Enter file name to upload>"; cin.width(sizeof(lfile)); // 10/31/2026: No overflow of lfile cin >> lfile; cout << "Enter remote file name>"; cin.width(sizeof(rfile)); // 10/31/2026: No overflow of rfile cin >> rfile; DiskFileB stream(lfile); if(!stream) { cout << "Could not open the " << lfile << " input file" << "\n" << flush; return; } FAU_t bytes; ftp->FTPPut((const char *)rfile, stream, bytes); if(!CheckError(ftp, 0)) return; cout << ftp->reply_buf << flush; cout << (long)bytes << " bytes transfered" << "\n" << flush; } int main(int argc, char **argv) { #ifdef __MSVC_DEBUG__ InitLeakTest(); #endif if(argc < 4) { cout << "Usage: " << argv[0] << " server username password [port]" << "\n" << flush; cout << "server = Your FTP server" << "\n" << flush; cout << "username = Your FTP account user name" << "\n" << flush; cout << "username = Your FTP account password" << "\n" << flush; cout << "port = Optional port number" << "\n" << flush; cout << "\n" << flush; cout << "Example: " << argv[0] << " ftp.xyz.com myname mypassword" << "\n" << flush; return 1; } char *server = argv[1]; char *username = argv[2]; char *password = argv[3]; unsigned short port = (unsigned short)21; if(argc == 5) port = atoi(argv[4]); gxsFTPClient ftp; ftp.SetTimeOut(60, 0); // Set a long time for remote servers cout << "\n" << flush; cout << "Connecting to ftp server" << "\n" << flush; ftp.ConnectClient((const char *)server, port); if(!CheckError(&ftp)) return 1; cout << ftp.reply_buf << flush; ftp.FTPLogin((const char *)username, (const char *)password); if(!CheckError(&ftp)) return 1; cout << ftp.reply_buf << flush; char key; Menu(); int rv = 1; while(rv) { if (!cin) { ClearInputStream(cin); if (!cin) { cout << "Input stream error" << "\n" << flush; return 0; } } cout << '>'; cin >> key; if (!cin) continue; switch(key) { case '?' : Menu(); break; case 'a' : ClearInputStream(cin); ASC(&ftp); break; case 'A' : ClearInputStream(cin); Active(&ftp); break; case 'b' : case 'B' : ClearInputStream(cin); BIN(&ftp); break; case 'c' : case 'C' : ClearInputStream(cin); ChDir(&ftp); break; case 'd' : case 'D' : ClearInputStream(cin); Delete(&ftp); break; case 'g' : case 'G' : ClearInputStream(cin); Get(&ftp); break; case 'h' : case 'H' : Menu(); break; case 'l' : ClearInputStream(cin); List(&ftp, 1); break; case 'L' : ClearInputStream(cin); List(&ftp, 0); break; case 'm' : case 'M' : ClearInputStream(cin); MkDir(&ftp); break; case 'n' : ClearInputStream(cin); ListDir(&ftp, 1); break; case 'N' : ClearInputStream(cin); ListDir(&ftp, 0); break; case 'p' : ClearInputStream(cin); Put(&ftp); break; case 'P' : ClearInputStream(cin); Passive(&ftp); break; case 'q' : case 'Q' : rv = 0; break; case 'r' : case 'R' : ClearInputStream(cin); RmDir(&ftp); break; case 's' : case 'S' : ClearInputStream(cin); Stat(&ftp); break; case 'v' : case 'V' : ClearInputStream(cin); Move(&ftp); break; case 'w' : case 'W' : ClearInputStream(cin); PWD(&ftp); break; case 'z' : case 'Z' : ClearInputStream(cin); Size(&ftp); break; default: cout << "Unrecognized command" << "\n" << flush; break; } } ftp.FTPLogout(); if(!CheckError(&ftp)) return 1; cout << ftp.reply_buf << flush; cout << "\n" << flush; ftp.Close(); return 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++20)
examples_modern/socket/ftp_client/modern.cpp 55 lines
#include <iostream> #include <string> #include <string_view> #include <vector> #include "../common/modern_net.h" #include "gxsftp.h" using namespace modern_net; std::vector<std::string> split_lines(std::string_view text) { std::vector<std::string> lines; for(std::size_t eol; (eol = text.find("\r\n")) != std::string_view::npos; text.remove_prefix(eol + 2)) if(eol) lines.emplace_back(text.substr(0, eol)); return lines; } int main(int argc, char **argv) { SocketLibrary lib; FakeServer fake; const bool real = argc > 3; std::string server = real ? argv[1] : "127.0.0.1"; int port = 21; if(!real) { fake.send("220 fake FTP ready\r\n").reply("331 password\r\n").reply("230 logged in\r\n") .data_listen().reply("227 Entering Passive Mode (127,0,0,1,%PORT%)\r\n") .reply("150 listing\r\n").data_send("README.txt\r\nsrc\r\nversion.txt\r\n") .sleep(100).send("226 done\r\n").reply("221 bye\r\n"); port = fake.start(); } gxsFTPClient ftp; ftp.SetTimeOut(10, 0); ftp.FTPPassive(); auto ok = [&ftp](int rv, std::string_view what) { if(rv != 0) std::cout << what << " failed: " << ftp.SocketExceptionMessage() << "\n"; return rv == 0; }; if(!ok(ftp.ConnectClient(server.c_str(), port), "connect") || !ok(ftp.FTPLogin(real ? argv[2] : "user", real ? argv[3] : "pass"), "login")) return 1; std::string list(64 * 1024, '\0'); if(!ok(ftp.FTPList(list.data(), unsigned(list.size()), 0), "list")) return 1; list.resize(list.find('\0')); for(const auto &name : split_lines(list)) std::cout << " " << name << "\n"; ok(ftp.FTPLogout(), "logout"); ftp.Close(); fake.join(); return 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
examples_modern/socket/common/modern_net.h 142 lines
#ifndef MODERN_NET_H #define MODERN_NET_H #include <chrono> #include <cstdio> #include <string> #include <thread> #include <vector> #if !defined(_WIN32) #include <arpa/inet.h> #include <csignal> #endif #include "gxsocket.h" namespace modern_net { inline void ignore_sigpipe() { #if !defined(_WIN32) std::signal(SIGPIPE, SIG_IGN); #endif } class SocketLibrary { // RAII for Winsock and friends public: SocketLibrary() { ok_ = probe_.InitSocketLibrary() == 0; } ~SocketLibrary() { probe_.ReleaseSocketLibrary(); } SocketLibrary(const SocketLibrary &) = delete; SocketLibrary &operator=(const SocketLibrary &) = delete; explicit operator bool() const { return ok_; } private: gxSocket probe_; bool ok_ = false; }; inline int bound_port(gxSocket &s) // After Bind() to port 0 { if(s.GetSockName() < 0) return -1; return int(ntohs(s.sin.sin_port)); } // Opens a listening socket on 127.0.0.1 and a free port. Returns the // port or -1. inline int listen_loopback(gxSocket &s, int backlog = 5) { if(s.InitSocket(SOCK_STREAM, 0, const_cast<char *>("127.0.0.1")) < 0) return -1; if(s.Bind() < 0 || s.Listen(backlog) < 0) return -1; return bound_port(s); } class FakeServer { public: enum class Kind { Send, Sleep, ReadLine, ReadHeader, ReadData, DataListen, DataSend }; struct Step { Kind kind; std::string data; }; FakeServer &send(std::string s) { steps_.push_back({Kind::Send, std::move(s)}); return *this; } FakeServer &sleep(int ms) { steps_.push_back({Kind::Sleep, std::to_string(ms)}); return *this; } FakeServer &read_line() { steps_.push_back({Kind::ReadLine, {}}); return *this; } FakeServer &read_header() { steps_.push_back({Kind::ReadHeader, {}}); return *this; } FakeServer &read_data() { steps_.push_back({Kind::ReadData, {}}); return *this; } FakeServer &reply(std::string s) { read_line(); return send(std::move(s)); } FakeServer &data_listen() { steps_.push_back({Kind::DataListen, {}}); return *this; } FakeServer &data_send(std::string s) { steps_.push_back({Kind::DataSend, std::move(s)}); return *this; } // Starts the script; returns the port or -1 int start() { port_ = listen_loopback(listener_, 1); if(port_ > 0) worker_ = std::jthread([this](std::stop_token st) { run(st); }); return port_; } void join() { if(worker_.joinable()) worker_.join(); } const std::string &received() const { return received_; } // After join() ~FakeServer() { join(); } private: bool wait_read(gxSocket &s, gxsSocket_t fd, std::stop_token &st) { for(int i = 0; i < 50 && !st.stop_requested(); i++) // Up to 5 s if(s.ReadSelect(fd, 0, 100000) > 0) return true; return false; } void run(std::stop_token st) { if(!wait_read(listener_, listener_.GetSocket(), st) || listener_.Accept() < 0) { listener_.Close(); return; } gxsSocket_t c = listener_.GetRemoteSocket(); for(const Step &step : steps_) { if(step.kind == Kind::Send) { std::string d = step.data; if(auto p = d.find("%PORT%"); p != std::string::npos) d.replace(p, 6, std::to_string(data_port_ / 256) + "," + std::to_string(data_port_ % 256)); if(listener_.Send(c, d.data(), int(d.size())) < 0) break; } else if(step.kind == Kind::Sleep) { std::this_thread::sleep_for(std::chrono::milliseconds(std::stoi(step.data))); } else if(step.kind == Kind::DataListen) { data_port_ = listen_loopback(data_, 1); } else if(step.kind == Kind::DataSend) { if(wait_read(data_, data_.GetSocket(), st) && data_.Accept() >= 0) { gxsSocket_t d = data_.GetRemoteSocket(); data_.Send(d, step.data.data(), int(step.data.size())); data_.Close(d); } data_.Close(); } else { // One of the reads std::string got; auto ends_with = [&got](std::string_view e) { return got.ends_with(e); }; while(wait_read(listener_, c, st)) { char ch; if(listener_.RawRead(c, &ch, 1) != 1) break; got += ch; if(step.kind == Kind::ReadLine && ch == '\n') break; if(step.kind == Kind::ReadHeader && ends_with("\r\n\r\n")) break; if(step.kind == Kind::ReadData && ends_with("\r\n.\r\n")) break; } received_ += got; if(got.empty()) break; // The client closed } } std::this_thread::sleep_for(std::chrono::milliseconds(50)); listener_.Close(c); listener_.Close(); } gxSocket listener_, data_; std::vector<Step> steps_; std::string received_; int port_ = -1, data_port_ = 0; std::jthread worker_; }; } // namespace modern_net #endif // MODERN_NET_H // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Build and run
cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20 cmake --build build-modern --target socket_ftp_client ./build-modern/socket_ftp_client
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
README.txt src version.txt