I'm using gethostbyname to get IP address by a computer name on a LAN, but sometimes it returns more than one IP for one name. But how can that be? And if that happens how to get _The_ IP to be used to connect to that particular PC?
You can check the IP, if you need a local address you can check whether your ip is:
Class A: 10.*.*.*
Class B: 172.*.*.*
or
Class C: 192.*.*.*
All of these Classes are LAN IP address types, if your IP doesnt fit any of these cases it means its an external WAN IP that people outside of your local network can connect to using the internet.
You can check the IP, if you need a local address you can check whether your ip is:
Class A: 10.*.*.*
Class B: 172.*.*.*
or
Class C: 192.*.*.*
All of these Classes are LAN IP address types, if your IP doesnt fit any of these cases it means its an external WAN IP that people outside of your local network can connect to using the internet.
This is by no means a hard-fast rule.
As to the OP's question, the first entry in h_addr_list should be the preferred address. A DNS can return multiple addresses for the same hostname according to the priority. gethostbyname() will order them in the priority order so just use the first entry.
the first entry in h_addr_list should be the preferred address. A DNS can return multiple addresses for the same hostname according to the priority. gethostbyname() will order them in the priority order so just use the first entry.
I thought that too, but unfortunately that's not always true. Here's my situation (see diagram attached):
If gethostbyname is ran from PC#1, it returns IPs in the following order:
1. For PC #3
2. For PC #2
3. For Wireless adapter from PC #2
If I take IP 1 it will direct me to PC #3 that I will not even be able to connect to (both LAN connections are done via cross-over ethernet cable and two network cards in PC #2).
So how can I resolve this situation?
As for kolkoo's suggestion, I agree that would not be a good way to hardcode it like that, since for sure it will not hold up on Vista with the introduction of IP6 addresses.
Sounds like you've got a non-standard setup at best. Your DNS must be really messed up too to give hostnames out in that manner. I'm afraid I've got no answer for you.
* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.