I spent hours trying to find out my issue, just found the solution as I was writing my question (it always help when you need to formalize your issue and explain it). I post it, hopefully it helps someone.
Using getaddrinfo, if I try to connect a socket to my server, doing (what I thought was) exactly what is being explained on tons of website aswell as in the man page sample code of getaddrinfo, it FAILS with a "connection timed out" error message: (Simplifying the code to be more concise)
void connect_UsingGetAddrInfo_Wrong (std::string host, unsigned short int port, int& socketfd)
{
//simplified loops & error handling for concision
int x;
int domain = AF_INET; // IP_v4
int socketType = SOCK_STREAM; // Sequenced, reliable, connection-based byte streams.
addrinfo hints, *addr;
//fine-tune hints according to which socket you want to open
hints.ai_family = domain;
hints.ai_socktype = socketType;
hints.ai_protocol = 0; // no enum : possible value can be read in /etc/protocols
hints.ai_flags = AI_CANONNAME | AI_ALL | AI_ADDRCONFIG;
x = getaddrinfo(hostname, NULL, &hints, &addr);
//shall rather loop on addr linked list, but this is not the topic here.
socketfd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
x = connect(socketfd, addr->ai_addr, addr->ai_addrlen);
}
However, I was able to connect a socket to the same server, using gethostbyname method.
void connect_UsingGetHostByName_Deprecated (std::string host, unsigned short int port, int& socketfd)
{
//simplified loops & error handling for concision
int x;
int domain = AF_INET; // IP_v4
int socketType = SOCK_STREAM; // Sequenced, reliable, connection-based byte streams.
struct hostent DNS, *r;
char buf[1024];
x = gethostbyname_r(hostname.c_str(), & DNS, buf, sizeof(buf), & r, & err));
socketfd = socket(domain, socketType, 0);
//server.
sockaddr_in server;
memset(&server, 0x00, sizeof(server));
server.sin_family=domain;
server.sin_port=htons(port);
memcpy(& server.sin_addr.s_addr, DNS.h_addr, (size_t) DNS.h_length);
x = connect(socketfd, (struct sockaddr *) & server, sizeof(server));
}
Running code shows that both version correctly retrieve the valid IP address of the server. Still the first one won't connect and will time out. Why ?