# getaddrinfo help



## Business_Woman (Sep 11, 2010)

Hello,

I am trying to write a simple C program for ip lookup.
Result now points to a struct wich holds the results of my lookup, but struct addrinfo itself contains a pointer to a struct of type sockaddr_in. So i have a pointer to a pointer to a struct ... How would you get the address from that?




```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>


int status = 0;

struct addrinfo hints *p,*result;

memset(&hints,0,sizeof hints);

hints.ai_family = AF_INET;
hints.ai_socktype = SOCKSTREAM;

status = getaddrinfo("www.freebsd.org",NULL,&hints,&result);
}
```


----------



## kpa (Sep 11, 2010)

Read the manual page of getaddrinfo(3), it has an example towards the end that explains how to walk trough the results list.


----------



## Business_Woman (Sep 11, 2010)

kpa said:
			
		

> Read the manual page of getaddrinfo(3), it has an example towards the end that explains how to walk trough the results list.



Why should i have to loop through the whole thing when i know which result i want?
It's a matter of pointer algebra


----------



## kpa (Sep 11, 2010)

Because the query might return more than one address. Always write your programs in a way that you don't assume anything about the results. That means you'll have to loop trough the list and figure out what is the result or results you need. There isn't much of pointer algebra if you want just the first result, the pointer result is already pointing to the first element of the list so result->ai_addr should be the address and so on.


----------



## Business_Woman (Sep 19, 2010)

Hm,

I found this and didn't quite understand it. What is the difference between 

```
return &(((struct sockaddr_in*)sa)->sin_addr);
```

and 

```
return &(struct sockaddr_in *)(sa->sin_addr);
```

?


----------



## brucec@ (Sep 20, 2010)

http://www.akkadia.org/drepper/userapi-ipv6.html has a good tutorial showing how to use getaddrinfo() etc.


----------



## expl (Sep 21, 2010)

Business_Woman said:
			
		

> Hm,
> 
> I found this and didn't quite understand it. What is the difference between
> 
> ...



In first return you assign type "struct sockaddr_in*" to "sa". In second you give that type to "sa->sin_addr". See where I am going? That kinda changes a lot how your code works.


----------



## Business_Woman (Sep 22, 2010)

expl said:
			
		

> In first return you assign type "struct sockaddr_in*" to "sa". In second you give that type to "sa->sin_addr". See where I am going? That kinda changes a lot how your code works.




Yes, i understand that. But sa->sin_addr is just a shorter way of writing *sa.sin_addr = ..
So is this the same as writing &((struct sockaddr *)*sa).sin_addr ?

And in the second case &((struct sockaddr *)*sa.sin_addr) 
?


----------

