server.c
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main(int argc, char **argv)
{
int sock;
struct addrinfo hints, *res, *resi;
char *port = "2727";
/* Get localhost information */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /** AF_UNSPEC **/
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_ADDRCONFIG;
if(getaddrinfo(NULL, port, &hints, &res) != 0) /* NULL fills up the local address */
error(EXIT_FAILURE, errno, "fatal error: getaddrinfo()");
/** FIX THIS: Iterate trough res, get a socket and try to bind it *
for(resi = res; resi != NULL; resi = resi->ai_next) {
/* Get a TCP socket to listen on *
if((sock = socket(resi->ai_family, resi->ai_socktype, resi->ai_protocol)) == -1) continue;
/* Try to bind the socket *
if(bind(sock, resi->ai_addr, resi->ai_addrlen) == 0) break;
/* Dismiss the failure and try the next one *
close(sock);
}
if(resi == NULL) error(EXIT_FAILURE, errno, "fatal error");
freeaddrinfo(res); **/
/* Get a TCP socket, bind and listen to it -- comment this */
if((sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1)
error(EXIT_FAILURE, errno, "fatal error: socket()");
if(bind(sock, res->ai_addr, res->ai_addrlen) == -1)
error(EXIT_FAILURE, errno, "fatal error: bind()");
if(listen(sock, 5) == -1)
error(EXIT_FAILURE, errno, "fatal error: listen()");
/* ----- */
while(1) {
int csock;
struct sockaddr addr;
socklen_t addrlen;
if((csock = accept(sock, &addr, &addrlen)) == -1)
error(EXIT_FAILURE, errno, "fatal error: accept()");
printf("Successfully accepted!\n");
}
return EXIT_SUCCESS;
}
client.c
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main(int argc, char **argv)
{
int sock;
struct addrinfo hints, *res;
char *addr = NULL, *port = "2727"; /* NULL fills up the local address */
/* Get a TCP socket to listen on */
if((sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
error(EXIT_FAILURE, errno, "fatal error: socket()");
/* Get server information */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_NUMERICSERV | AI_ADDRCONFIG;
if(getaddrinfo(addr, port, &hints, &res) != 0)
error(EXIT_FAILURE, errno, "fatal error: getaddrinfo()");
if(connect(sock, res->ai_addr, res->ai_addrlen) == -1)
error(EXIT_FAILURE, errno, "fatal error: connect()");
freeaddrinfo(res);
return EXIT_SUCCESS;
}
The code works as it is, but trying to do things as in the getaddrinfo() manpage leads up to the invalid argument error, which is the commented FIXME code. I'm not sure what causes this behavior. Just comment/uncomment the code in server.c and try it out yourself.