I am trying to develop a simple UNIX server, that is not limited to IPv4. However, my sample code "hangs" on accept() call and when I try to telnet, I get "Connection refused" on both 127.0.0.1 and ::1.
My code (I marked what I considered most relevant with /**/)
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <unistd.h>
#include <assert.h>
main(int argc, char **argv) {
struct addrinfo hi;
memset(&hi, 0, sizeof(hi));
hi.ai_family = AF_UNSPEC;
hi.ai_socktype = SOCK_STREAM;
hi.ai_flags = AI_PASSIVE;
struct addrinfo *r, *rorig;
char * port = "88";
/**/
if (0 != getaddrinfo(NULL, port, &hi, &r))/**/ {
perror("ERROR getaddrinfo");
exit(EXIT_FAILURE);
}
int socket_fd;
for (rorig = r; r != NULL; r = r->ai_next) {
/**/socket_fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);/**/
if (0 != bind(socket_fd, r->ai_addr, r->ai_addrlen)) break;
}
freeaddrinfo(rorig);
if (r == nullptr) {
perror("ERROR binding");
exit(EXIT_FAILURE);
}
fprintf(stdout, "LISTEN, fd: %d\n",socket_fd);
if (listen(socket_fd, 10) == -1) {
perror("listen ERROR");
exit(EXIT_FAILURE);
}
for (;;) {
fprintf(stdout, "ACCEPT\n");
/**/int new_fd = accept(socket_fd, NULL, NULL);/**/
if (new_fd == -1) {
perror("accept ERROR");
exit(EXIT_FAILURE);
}
fprintf(stdout, "Opened a file descriptior %d", new_fd);
}
}
I reviewed related questions here, for example Unix C socket server not accepting connections but none used getaddrinfo aproach and as to my knowledge, they were always limited to IPv4.
Any help would be appreciated.