Hello TCP Client

suggest change

This program is complementary to the Hello TCP Server program. You can run either of them to check the other. The program flow has a lot in common with the Hello TCP server, so take a look at that too.

Here’s the code -

#include <cstring>
#include <iostream>
#include <string>

#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>


int main(int argc, char *argv[])
{
    // Now we're taking an ipaddress and a port number as arguments to our program
    if (argc != 3) {
        std::cerr << "Run program as 'program <ipaddress> <port>'\n";
        return -1;
    }
auto &ipAddress = argv[1];
auto &portNum   = argv[2];

addrinfo hints, *p;
memset(&hints, 0, sizeof(hints));
hints.ai_family   = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags    = AI_PASSIVE;

int gAddRes = getaddrinfo(ipAddress, portNum, &hints, &p);
if (gAddRes != 0) {
    std::cerr << gai_strerror(gAddRes) << "\n";
    return -2;
}

if (p == nullptr) {
    std::cerr << "No addresses found\n";
    return -3;
}

// socket() call creates a new socket and returns its descriptor
int sockFD = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockFD == -1) {
    std::cerr << "Error while creating socket\n";
    freeaddrinfo(p);
    return -4;
}

// Note: there is no bind() call as there was in Hello TCP Server.
// The client does not need a fixed port number, so connect()
// binds it to an ephemeral port.

// connect() call tries to establish a TCP connection to the specified server
int connectR = connect(sockFD, p->ai_addr, p->ai_addrlen);
if (connectR == -1) {
    close(sockFD);
    freeaddrinfo(p);
    std::cerr << "Error while connecting socket\n";
    return -5;
}

std::string reply(15, ' ');

// recv() call tries to get the response from server
// BUT there's a catch here, the response might take multiple calls
// to recv() before it is completely received
// will be demonstrated in another example to keep this minimal
auto bytes_recv = recv(sockFD, &reply.front(), reply.size(), 0);
if (bytes_recv == -1) {
    std::cerr << "Error while receiving bytes\n";
    close(sockFD);
    freeaddrinfo(p);
    return -6;
}
if (bytes_recv >= 0)
    reply.resize(static_cast<std::string::size_type>(bytes_recv));

std::cout << "\nClient received: " << reply << std::endl;
close(sockFD);
freeaddrinfo(p);

return 0;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents