这些IP地址来自哪里?

时间:2009-06-14 05:59:09

标签: c unix network-programming

#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);
}

当我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我在防火墙下运行,所以我的服务器地址是192.168.101,我的本地机器是192.168.1.104

修改 我怀疑问题区域是函数调用

inet_ntop(AF_INET, 
                      their_addr.sa_data,
                      ipaddr, sizeof ipaddr);

这是将存储的IP地址转换为字符串的地方。

1 个答案:

答案 0 :(得分:2)

inet_ntop期望一个struct in_addr指针作为第二个参数,所以尝试这样的事情:

inet_ntop(AF_INET, &((struct sockaddr_in*)&their_addr)->sin_addr,
                                  ipaddr, sizeof ipaddr);