Click here to Skip to main content
Click here to Skip to main content
 

How To Get IP Address Of A Machine

By , 1 Feb 2001
 

Introduction

This article is not a technical overview or large discussion. It is like a collection of tips on how you can get the IP address or host name of a machine. In the Win32 API this could be accomplished using the NetWork API. And this is still true in the .NET framework. The only difference is finding and understanding what namespace and class to use to accomplish this task. In the .NET framework the NetWork API is available in the System.Net namespace. The DNS class in the System.Net namespace can be used to get the hostname of a machine or get the IP address if the hostname is already known. The DNS class provides a simple domain name resolution functionality. The DNS class is a static class that provides access to information from the Internet Domain Name System (DNS). The information returned includes multiple IP addresses and aliases if the host specified has more than one entry in the DNS database. The list is returned as a collection or an array of IPAddress objects. The following section is the code that shows how to obtain the IP address for a given host name.

DNSUtility Code

namespace NKUtilities 
{
    using System;
    using System.Net;
    
    public class DNSUtility
    {
        public static int Main (string [] args)
        {
        
          String strHostName = new String ("");
          if (args.Length == 0)
          {
              // Getting Ip address of local machine...
              // First get the host name of local machine.
              strHostName = DNS.GetHostName ();
              Console.WriteLine ("Local Machine's Host Name: " +  strHostName);
          }
          else
          {
              strHostName = args[0];
          }
          
          // Then using host name, get the IP address list..
          IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
          IPAddress [] addr = ipEntry.AddressList;
          
          for (int i = 0; i < addr.Length; i++)
          {
              Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
          }
          return 0;
        }    
     }
}

What The Code Does

If you want to obtain the hostname of the local machine, then call the GetHostName method without a parameter. Then use the resulting hostname as a parameter to the GetHostByName method to get the list of IPAddresses that may be associated with the hostname. Then iterate through the collection of addresses to write out the IP Addresses associated with the hostname.

Reminders

Make sure that you include the System.Net namespace in your code; otherwise the compiler will not know where to look for the DNS class. Also when you use VisualStudio.NET for creating the project, make sure that you have the System.NET.Dll in your reference list. For more information on the DNS class and System.Net namespace, please refer to the online documentation for the .NET SDK.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Naveen K Kohli
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralThis is very good article.memberJayesh Sorathia7 Aug '12 - 21:55 
This is very good article.
Here is a link for Get Hostname from IPAddress from C# and VB.Net Examples.
Visit this link. Click Here...
QuestionConsole closingmemberArjun Menon U.K30 Jun '12 - 2:36 
HI Naveen Thanks for the code you provided but when i run the code the terminal runs and closes by itslef.. How can i view the result since the console closes automatically?
GeneralMy vote of 2memberhlsnnet2 Apr '12 - 20:52 
top
Questionreferences of your articlemvpMd. Marufuzzaman25 Dec '11 - 7:41 
Hi,
Given code snippets also available at http://stackoverflow.com/questions/1069103/how-to-get-my-own-ip-address-in-c[^]
probably both are same, and I think you forgot to add the references.
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralInetAddressmemberPrerna Sancheti6 May '11 - 5:00 
How to get ip address of computers in network.
GeneralMy vote of 2memberRaviSant6 Jan '11 - 0:34 
not much informative.
Please also describe other ways to accomplish same.
GeneralMy vote of 3memberLibin Jose chemperi6 Dec '10 - 23:15 
vc
GeneralMy vote of 1memberJörgen Sigvardsson9 Jun '09 - 20:11 
It's just wrong. Relying on DNS to get your local IP addresses has so many gotchas involved that it's scary.
GeneralRe: My vote of 1memberPRMan!!!24 Sep '09 - 8:26 
And the right way is?
GeneralRe: My vote of 1memberDizZ21 May '10 - 6:07 
You can try with :
System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetIPProperties().UnicastAddresses[0].Address
 
The first index is if you have multiple network cards and the second index is if you have multiple ip addresses on the same network card
 
Good luck
AnswerRe: My vote of 1memberKenneth McKnight15 Jun '10 - 21:41 
You're really right, DizZ!
It's just the better way, but not available in CF.net.
 
For all are needing a performant way on mobile devices, have a look here:
http://www.pinvoke.net/default.aspx/iphlpapi/GetAdaptersAddresses.html[^]
General[newbie]memberjon_8029 Mar '09 - 4:05 
I'm trying to follow your code however, I'm having some trouble figuring out what code is required to return the IP address.
 
When I try to use Dns (System.Net namespace), no further methods are being show by VS 2008. Any ideas?
 
Confused | :confused:
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    private string ClientIPAddress { 
       ..er?
    }
}
 
Environment
ASP.NET with .NET 3.5 SP1
VS 2008 SP1
IIS7
 
Jon

GeneralRe: [newbie]memberByteBlocks29 Mar '09 - 7:27 
Hello,
Please usse this link to get latest code snippet.
 
http://www.byteblocks.com/post/2009/03/06/How-to-get-IP-address-of-machine.aspx[^]
GeneralRe: [newbie] [modified]memberjon_8030 Mar '09 - 12:10 
Thanks, that was useful, however do you have any idea on why VS does not like 'StringCollections'?
 
Imports System.Net
Imports System.Collections 
 
//this is just a guess, however it's incorrect, because System.Collections does not seem to have StringCollection...see related links 

Module Module1
 
    Sub Main()
 
    End Sub
 
    Private Function GetIPs() As StringCollection
        Dim localIP = New StringCollection()
        Dim localHostName = Dns.GetHostName()
        Dim hostEntry = Dns.GetHostEntry(localHostName)
        ' Grab all ip addesses.
        For Each ipAddr As IPAddress In hostEntry.AddressList
            localIP.Add(ipAddr.ToString())
        Next
        GetIPs = localIP
    End Function
 

This simple code snippet seems to work for IPv4 addresses:
 
Imports System.Net
Imports System.Collections
 
Module Module1
 
    Sub Main()
        Dim localHostName = Dns.GetHostName()
        Dim hostEntry = Dns.GetHostEntry(localHostName)
 
        For Each ipAddr As IPAddress In hostEntry.AddressList
            Console.WriteLine(ipAddr)
        Next
    End Sub
 
Some "fun" with C# / ASP.NET
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Collections;
 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        String _localHostName = Dns.GetHostName();
        IPHostEntry _hostEntries = Dns.GetHostEntry(_localHostName);
 
        foreach (IPAddress _IPAddress in _hostEntries.AddressList) {
            ListBox1.Items.Add( _IPAddress.ToString());
        }
 
    }
}
 

Environment notes
------------------
Visual Studio 2008
.NET 3.5 SP1
Visual Basic.NET / C#
 

Related links:
 
http://social.msdn.microsoft.com/Search/en-US/?query=system.collections.stringcollections&ac=3
 
Jon
modified on Monday, March 30, 2009 6:37 PM

GeneralRe: [newbie]memberByteBlocks30 Mar '09 - 14:00 
StringCollecion is defined in System.Collections.Specialized
Generalhellomemberjr_jamesrobert016 Jun '08 - 11:45 
do you know how to code a website like ebay.com other website lke that.contact me at jr_jamesrobert01@yahoo.com
Questionhow how u therememberjr_jamesrobert016 Jun '08 - 7:28 
please how can i code a website like ebay
QuestionWhat I'd really like to see is...membermycal27 Sep '07 - 8:24 

A way to get the local IP address that would be used to connect to somewhere without having to connect.
 
So if you have a machine that has a bunch of IP addresses, you can open a TCP connection and then query your IP address from the connection information.
 
But What I'd like to see is a way you could query the system to give you the local IP address that it would use to connect to a remote address.
 
-M
 

GeneralIPv6 (::1) issue with this code.memberdurkpurk28 Jul '07 - 1:03 
I spent quite some time on figuring out why my code (which resembles the code given in this article) wouldn't work on 'all' computers.
 
The retrieved IP address was "::1". This appears to occur on computers with IPv6 enabled and "::1" is the internal loopback address, which can be used for testing. It is not the IP address which I was looking for.
 
The array of IPAddress's will have this IPv6 internal loopback address as first 'unusable' entry for IPv6 eabled systems whereas this first entry used to be the address we were looking for. I see a lot of code, also here on codeproject, which relies on the fact that the first IPAddress array entry is OK, thay all just take addr[0] as found IP address.
 
For your code to be IPv6 'compliant' (not fully, that is quitte something different, but at least compliant for IPv6 tunneling systems) you must check if the found address is the one you looking for.
 
Check on AddressFamily is not) InterNetworkV6) and IPAddress.IsLoopback.
 
Hope this saves you my headaches on this issue...
 

 
As an example...(a bit of a mess, but it serves it's purpose)....
 
public string getAddress()
{
// First get the host name of local machine.
String strHostName = "";
strHostName = Dns.GetHostName();
 
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
 
log("Local host name: " + strHostName);
// address must be IpV4 (for our appl.) and not the loopback address
for (int i = 0; i < addr.Length; i++)
{
log(" IP Address[" + i + "]: " + addr[i].ToString());
if (addr[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { log("-----!! IpV6 address"); }
if (IPAddress.IsLoopback(addr[i])) { log("-----!! loopback address"); }
}
 
string selectedAddress = String.Empty;
for (int i = 0; i < addr.Length; i++)
{
if (addr[i].AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
{
if (!IPAddress.IsLoopback(addr[i]))
{
selectedAddress = addr[i].ToString();
log(" using: " + selectedAddress + " (index: " + i + ")");
break;
}
}
}
 
if (selectedAddress == String.Empty) { log("!!! No useable network addres found !!!"); }
 
return (selectedAddress);
}
 


GeneralRe: IPv6 (::1) issue with this code.memberMonir Sabbagh21 Apr '09 - 23:16 
Great, thank you
GeneralRe: IPv6 (::1) issue with this code.memberIvanGB0016 Jul '12 - 3:03 
So far, the best and complete solution found.
Thank you!
Generalquestion in getting system informationmembervarghesh17 Mar '07 - 21:18 
Hai,
i want to get system information including all hardware and software devices. i don't have any idea about this module. Can anybody guide me how can i get such data using codings in .net framework
GeneralGet all IPAddress in the networkmemberWakwak Chimera3 Jan '07 - 19:25 
Hi.
 
I was wondering if there is a way to use the same routine to get all the available IP address in a given LAN using the same codes?
 
Will someone please show me how? Thanks Smile | :)
QuestionHow To Get IP Address &amp; MAC address Of (Barcode Printer) of the Network?memberJan Palmer3 Jan '07 - 18:46 
I tried running the code below but it doesn't give me the IP address I need for my Barcode Network Printer.
 
DirectorySearcher srch = new DirectorySearcher();
DirectoryEntry entry = srch.SearchRoot;
string domain = (string)entry.Properties["name"][0]; //DC name
 
DirectoryEntry DomainEntry = new DirectoryEntry("WinNT://" + domain);
DomainEntry.Children.SchemaFilter.Add("computer");
 

// To Get all the System names And Display with the Ip Address
foreach (DirectoryEntry machine in DomainEntry.Children)
{
 
string[] Ipaddr = new string[3];
Ipaddr[0] = machine.Name;
// string guid = machine.Guid.ToString();
 
System.Net.IPHostEntry Tempaddr = null;
Console.WriteLine(">" + Ipaddr[0]); // + " " + guid);
try
{
//Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByAddress(machine.Name);
Tempaddr = (System.Net.IPHostEntry)Dns.GetHostEntry(machine.Name); //GetHostByName(
}
catch (Exception ex)
{
// IPx.Add(machine.Name);
continue;
}
System.Net.IPAddress[] TempAd = Tempaddr.AddressList;
foreach (IPAddress TempA in TempAd)
{
Ipaddr[1] = TempA.ToString();
//if (Ipaddr[1].ToString() == "10.25.1.222") { Console.WriteLine("found sato printer."); break; }
 
byte[] ab = new byte[6];
int len = ab.Length;
 
// This Function Used to Get The Physical Address
int r = SendARP((int)TempA.Address, 0, ab, ref len);
string mac = BitConverter.ToString(ab, 0, 6);
 
Ipaddr[2] = mac;
 
}
 
Console.WriteLine("\t\t" + Ipaddr[2].ToString().Trim() + "\t " + Ipaddr[1].ToString().Trim() + "\t\t " + Ipaddr[0].ToString().Trim() + " ");
 
}
 

I believe this code is all about searching for the assigned computer ip connected to the network. But my real question is,Is there a code in C# that actually searches for all the assigned network including hosts addresses? Its more than a week since I have been trying to solve this problem.. Confused | :confused: Dead | X|
 

Can anyone willing to challenge my question?
 
Thank you and Happy New Year to all!!
 
you can also email me at janverge@gmail.com

GeneralIP CollectionmemberDragon Slayer8 Jul '06 - 1:47 
first of all thank you very much,
 
you said "The information returned includes multiple IP addresses and aliases if the host specified has more than one entry in the DNS database"
 
One day I have queried the DNS and returned more than one IP, my machine was then named "TOSHIBA", I changed it to some thing like "my000000" then I logged in to the network and query the DNS again and the result was only one IP which is my machine IP address. How do you explain this and how can I identify my machine IP in case it returns more than one IP.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 2 Feb 2001
Article Copyright 2000 by Naveen K Kohli
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid