gethostbyname()未知错误

时间:2016-10-31 23:11:05

标签: c sockets

我正在尝试从给定域接收IP地址。域从客户端发送到本地服务器,在服务器中我需要找到IP。

这是我的代码:

int hostname_to_ip(char * hostname, char* ip)
{
    struct hostent *he;
    struct in_addr **addr_list;
    int i;

    if ( (he = gethostbyname( hostname ) ) == NULL) 
    {
        herror("gethostbyname");
        return 1;
    }

    addr_list = (struct in_addr **) he->h_addr_list;

    for(i = 0; addr_list[i] != NULL; i++) 
    {
        strcpy(ip , inet_ntoa(*addr_list[i]) );
        return 0;
    }

    return 1;
}

int main() {
    int s;
    struct sockaddr_in server, client;
    int c, l, i;
    char buffer[100];
    char ip[100];
    struct hostent *ipAddress;
    struct in_addr **addr_list;

    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s < 0) {
        printf("Socket creation error!\n");
        return 1;
    }

    memset(&server, 0, sizeof(server));
    server.sin_port = htons(1234);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;

    if (bind(s, (struct sockaddr *) &server, sizeof(server)) < 0) {
        printf("Bind error!\n");
        return 1;
    }

    l = sizeof(client);
    memset(&client, 0, sizeof(client));

    for (i = 0; i < 10000; i++) {
        recvfrom(s, &buffer, sizeof(buffer), MSG_WAITALL, (struct sockaddr *) &client, &l);
        printf("%s\n", "Client connected: ");
        printf("%s\n", buffer);
        char *host = buffer;
        hostname_to_ip(buffer, ip);
        printf("%s\n", ip);
    }

    close(s);
}

收到的消息是:未知主机,我找不到原因。

我确信我会发送一个正确的域名,例如&#34; www.google.com&#34;

1 个答案:

答案 0 :(得分:0)

看起来这个for循环格式不正确:

for(i = 0; addr_list[i] != NULL; i++)  {
    strcpy(ip , inet_ntoa(*addr_list[i]) );
    return 0; 
}

它将在第一次迭代后纾困并返回。

我会先解决这个问题。