Streams in IPWorks SSH and SFTP
The C++ editions of IPWorks SSH and IPWorks SFTP support stream-based file transfers by allowing you to implement custom stream classes derived from the provided abstract stream interfaces.
By implementing these interfaces, you can control how data is read, written, and processed during transfer operations. Refer to the product documentation for details on the stream interface.
The following example demonstrates a simple stream implementation that provides data from memory and uses SetUploadStream to upload the content to an SFTP server without reading from a file.
#include <stdio.h>
#include <string.h>
#include "../../include/ipworkssftp.h"
const char* fileData = "hello world.";
// Our stream will support reading, but not seeking or writing.
class SftpReadStream : public IPWorksSFTPStream {
int pos = 0;
int len = (int)strlen(fileData);
int readBytes = 0;
public:
bool CanRead() { return true; }
bool CanSeek() { return false; }
bool CanWrite() { return false; }
int64 GetLength() { return len; }
void Close() {
pos = 0;
readBytes = 0;
}
int Flush() {
pos = 0;
readBytes = 0;
return 0;
}
int Read(void* buffer, int count) {
readBytes = 0;
char* out = (char*)buffer;
while (pos < len && readBytes < count) {
out[readBytes] = fileData[pos];
readBytes++;
pos++;
}
return readBytes;
}
int64 Seek(int64 offset, int seekOrigin) {
// Must always support getting current position even if seeking is not supported.
if (offset == 0 && seekOrigin == 1) return pos;
return -1;
}
int Write(const void* buffer, int count) {
return -1; // Writing is not supported.
}
};
class MySftpClient : public SFTPClient {
public:
virtual int FireSSHServerAuthentication(SFTPClientSSHServerAuthenticationEventParams* e) {
printf("Connecting to server. Fingerprint: [%s]. Accepting.\n", e->Fingerprint);
e->Accept = true;
return 0;
}
};
int main()
{
MySftpClient client;
SftpReadStream inputStream;
client.SetSSHUser("ExampleUser");
client.SetSSHPassword("ExamplePassword");
client.SSHLogon("sftp.server", 22);
if (client.GetLastErrorCode()) goto done;
client.SetUploadStream(&inputStream);
client.SetRemoteFile("helloworld.txt");
client.Upload();
if (client.GetLastErrorCode()) goto done;
client.SSHLogoff();
done:
if (client.GetLastErrorCode()) {
printf("Error: [%i] %s\n", client.GetLastErrorCode(), client.GetLastError());
}
printf("done.\n");
return 0;
}
We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.