#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
//set up hints
struct addrinfo hints;
struct addrinfo *res;
struct sockaddr their_addr;
socklen_t sin_size = sizeof their_addr;
char ipaddr[INET6_ADDRSTRLEN];
int sockfd, new_fd;
int sent;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, argv[1], &hints, &res);
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
//bind a port to listen on
bind(sockfd, res->ai_addr, res->ai_addrlen);
listen(sockfd, 10);
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
inet_ntop(AF_INET,
their_addr.sa_data,
ipaddr, sizeof ipaddr);
printf("Connection recieved from %s", ipaddr);
sent = send(new_fd, "Hello, world!", 13, 0);
}
This is the output from server when I telnet in:
tyler@tkahn-server:~$ ./server_setup 1299
Connection recieved from 186.32.0.0
tyler@tkahn-server:~$ ./server_setup 1299
^C
tyler@tkahn-server:~$ ./server_setup 1290
Connection recieved from 231.237.0.0
tyler@tkahn-server:~$ ./server_setup 1290
Connection recieved from 231.241.0.0
tyler@tkahn-server:~$
BTW I'm running under a firewall so my server address is 192.168.101 and my local machine is 192.168.1.104
EDIT I suspect the troubled area is the function call
inet_ntop(AF_INET,
their_addr.sa_data,
ipaddr, sizeof ipaddr);
This is where the stored ip address is converted into a string.