1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
#ifndef WIN32
#include <arpa/inet.h>
#include <netdb.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <udt.h>
using namespace std;
int main(int argc, char* argv[])
{
if ((argc != 5) || (0 == atoi(argv[2])))
{
cout << "usage: recvfile server_ip server_port remote_filename local_filename" << endl;
return -1;
}
// use this function to initialize the UDT library
UDT::startup();
struct addrinfo hints, *peer;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
UDTSOCKET fhandle = UDT::socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
if (0 != getaddrinfo(argv[1], argv[2], &hints, &peer))
{
cout << "incorrect server/peer address. " << argv[1] << ":" << argv[2] << endl;
return -1;
}
// connect to the server, implict bind
if (UDT::ERROR == UDT::connect(fhandle, peer->ai_addr, peer->ai_addrlen))
{
cout << "connect: " << UDT::getlasterror().getErrorMessage() << endl;
return -1;
}
freeaddrinfo(peer);
// send name information of the requested file
int len = strlen(argv[3]);
if (UDT::ERROR == UDT::send(fhandle, (char*)&len, sizeof(int), 0))
{
cout << "send: " << UDT::getlasterror().getErrorMessage() << endl;
return -1;
}
if (UDT::ERROR == UDT::send(fhandle, argv[3], len, 0))
{
cout << "send: " << UDT::getlasterror().getErrorMessage() << endl;
return -1;
}
// get size information
int64_t size;
if (UDT::ERROR == UDT::recv(fhandle, (char*)&size, sizeof(int64_t), 0))
{
cout << "send: " << UDT::getlasterror().getErrorMessage() << endl;
return -1;
}
if (size < 0)
{
cout << "no such file " << argv[3] << " on the server\n";
return -1;
}
// receive the file
fstream ofs(argv[4], ios::out | ios::binary | ios::trunc);
int64_t recvsize;
int64_t offset = 0;
if (UDT::ERROR == (recvsize = UDT::recvfile(fhandle, ofs, offset, size)))
{
cout << "recvfile: " << UDT::getlasterror().getErrorMessage() << endl;
return -1;
}
UDT::close(fhandle);
ofs.close();
// use this function to release the UDT library
UDT::cleanup();
return 0;
}
|