0

This question is related to Given a Uri value how can one check whether it refers the local machine?, which did not see a satisfactory resolution.

My need is simple, I want to discover the IP addresses (may be more than one if there are multiple network cards) as well as the host names of the local machine without making any network round-trips. Meaning only the information appearing in the local tables, no DNS queries. BTW, the domain names must be discovered as well.

On second thought, I can do with the following method:

bool IsLocalAddress(string address);

Which accepts IP, host name or host + domain name and returns true iff the address refers the local machine. Again, please take into account multiple NICs and domains.

Thanks a lot in advance.

P.S.

I prefer C# code samples.

Community
  • 1
  • 1
mark
  • 59,016
  • 79
  • 296
  • 580
  • Once you bring DNS into it, all bets are off. The machine cannot know all the DNS entries there may be registered for it. – Tim Lloyd Feb 01 '11 at 19:42
  • Right, but there should be a local cache on the machine itself. I am wondering if it is possible to examine this cache. – mark Feb 01 '11 at 20:23

2 Answers2

1

There's a sample that looks interesting here.

Bob Moore
  • 6,788
  • 3
  • 29
  • 42
  • +1 for the link. However, can I convert the given IPs to respective host names without any network queries? My guess is that I should be, because the IPs are local, but I am not sure. In addition, there is the issue of domain. An address can be host+domain and it still may reference the local machine. – mark Feb 01 '11 at 13:01
  • Found the .NET equivalent - http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.getallnetworkinterfaces.aspx – mark Feb 01 '11 at 20:48
  • Even better - Dns.GetHostAddresses(string.Empty) – mark Feb 02 '11 at 10:19
0

Using Python you could do this:

import socket
socket.gethostname() # hostname
socket.gethostbyname(gethostname())  # host ip addr

A bit of googling shows that the Windows API contains two functions of the same name so any language could use similar code.

If you are writing Windows specific code, then you should use the WMI class, for instance Win32_NetworkAdapterConfiguration provides information on multiple interfaces and multiple ip addresses per interface.

Michael Dillon
  • 31,973
  • 6
  • 70
  • 106
  • How does it answer the question of multiple NICs? If the machine has more than one network card, then there are more than one IP address with possibly more than one host name. – mark Feb 01 '11 at 12:25