views:

233

answers:

1
#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.

+2  A: 

inet_ntop expects a struct in_addr pointer as the second argument, so try something like this:

inet_ntop(AF_INET, &((struct sockaddr_in*)&their_addr)->sin_addr,
                                  ipaddr, sizeof ipaddr);
Gerald
thanks! it workedwhat does the 's' mean in sin_*?
Tyler
Basically it just stands for "sockaddr_in". sockaddr works kinda like a union, in this case the sa_data[14] translates to a unsigned short port (sin_port) followed by a 4 byte address (sin_addr), followed by 8 dead bytes.
Gerald