#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()
{
char *ipAddress = (char *)"127.0.0.1";
char *portNum = (char *)"8888";
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 == NULL)
{
std::cerr << "No addresses found\n";
return -3;
}
int sockFD = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockFD == -1)
{
std::cerr << "Error while creating socket\n";
return -4;
}
int connectR = connect(sockFD, p->ai_addr, p->ai_addrlen);
if (connectR == -1)
{
close(sockFD);
std::cerr << "Error while connecting socket\n";
return -5;
}
char recv_data[204800];
while (1)
{
auto bytes_recv = recv(sockFD, &recv_data, 204800, 0);
if (bytes_recv > -1)
{
// char *payload = (char *)malloc(bytes_recv);
// memcpy(payload, recv_data, bytes_recv);
std::cout << recv_data << std::endl;
memset(recv_data, 0, 204800);
}
}
close(sockFD);
freeaddrinfo(p);
return 0;
}
https://riptutorial.com/cplusplus/example/24000/hello-tcp-client