How to get the network name using getaddrinfo()

Feb 8, 2009 at 1:11am
Hi Guys,

I am sorry in advance if this is not the right place to post this topic. Having said that, here is my problem:
I am using the code below to get the host name or IP of the machine I am starting the program at: (for ex. test.cs.test.edu or 192.168.1.100)
Here is the code that I am using
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
int main(int argc, char **argv) { 

//Usage of getaddrinfo() 

int status; 
struct addrinfo hints, *p; 
struct addrinfo *servinfo;  //will point to the result 
char ipstr[INET6_ADDRSTRLEN];

memset(&hints, 0, sizeof hints); // make sure the struct is empty 

hints.ai_family   = AF_UNSPEC;    
hints.ai_socktype = SOCK_STREAM;  
hints.ai_flags    = AI_PASSIVE;  

if ((status = getaddrinfo(NULL, "4321", &hints, &servinfo)) == -1) { 
    fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status)); 
    exit(1); 
}       

for (p=servinfo; p!=NULL; p=p->ai_next) { 
    struct in_addr  *addr;  
    if (p->ai_family == AF_INET) { 
        struct sockaddr_in *ipv = (struct sockaddr_in *)p->ai_addr; 
        addr = &(ipv->sin_addr);  
    } 
    else { 
        struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr; 
        addr = (struct in_addr *) &(ipv6->sin6_addr); 
    }
        inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr); 
 
} 
    cout<<"Address:"<<ipstr<<endl; 
    freeaddrinfo(servinfo); 

return 0;

 }


It results as 0.0.0.0
I don't know what is the problem. Any help would be greatly appreciated.

Thanks
Feb 9, 2009 at 11:45am
Is "4321" a known host or just a test name?
Feb 9, 2009 at 7:27pm
I just used it as a test
Feb 10, 2009 at 9:52am
If an unknown host name is given, it won't have an address.
Last edited on Feb 10, 2009 at 12:43pm
Feb 10, 2009 at 4:04pm
Doesn't it work the way like if we do not provide it an address, it takes the local address?
Feb 10, 2009 at 8:16pm
No. It'll try and do a look-up and fail. Thus returning you an equal to null address.

Otherwise, everytime you opened your browser and mis-typed a URL, it'd try and connect to your local server. Luckily it doesn't.
Last edited on Feb 10, 2009 at 8:16pm
Topic archived. No new replies allowed.