2013-03-27 50 views
2

我剛開始使用C編程。這應該是一個簡單的程序,但我得到了分段錯誤。我將不勝感激任何HLEP使用gethostbyname

問候,

胡安

#include <string.h> 

#include <stdio.h> 
#include <stdlib.h> 
#include<errno.h> 
#include<netdb.h> 
#include<sys/socket.h> 
#include<netinet/in.h> 


int main(int argc, char **argv) 
{ 

    struct hostent *hp; 
    struct in_addr **addr_list; 

    if ((hp = gethostbyname("www.yahoo.ca")) == NULL) 
    { 
    printf("gethostbyname() failed\n"); 
    } 
    else 
    { 
    printf("Official name = %s\n", hp->h_name); 

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

    unsigned int i = 0; 
    while (addr_list[i] != NULL) 
    { 
     printf("%s\n",inet_ntoa(*((struct in_addr *)hp->h_addr))); 
     i++; 

    } 
    } 
} 

這裏是如何將節目叫:

[email protected]:~/Documents$ ./a.out 
Official name = any-rc.a01.yahoodns.net 
Segmentation fault (core dumped) 
[email protected]:~/Documents$ 
+0

在哪一點你會得到seg故障?寫代碼不會幫助... – Anshul 2013-03-28 04:30:17

回答

3

相反的hp->h_addr你可能想:

printf("%s\n", inet_ntoa(*addr_list[i])); 

作爲一個附註,gethostbyname已過時:您應該使用getaddrinfo。你會注意到,標準的新版本甚至沒有提到gethostbyname

+0

我同意這一點。 h_addr是addr_list [0]的別名,所以要糾正*你可能寫的printf(「%s \ n」,inet_ntoa(hp-> h_addr))的語法*,但實際上你確實想通過addr_list迭代。 – 2013-03-27 22:44:31