Monday, April 13, 2009

C#: get IP address of the system by hostname

i thought this was a very useful program for people who are trying to read the IP address of a system in a programmatic manner.

I use .NET-FRAMEWORK 2.0


using System;
using System.Net;
class getIP
{

static void Main(string[] args) {
string machine_name = Dns.GetHostName();
IPHostEntry host = Dns.GetHostByName(machine_name);

for (int i=0; i < host.AddressList.Length; i++){
Console.WriteLine(host.AddressList[i]);
}
Console.ReadLine();
}

}
if u were to use .NET-FRAMEWORK 3.5 the GetHostByName is deprecated....its obsolete.... u gotta use GetHostEntry...... i dunno why that was deprecated....it was simple to remember "GetHostByName" is a very obvious name......
using System;
using System.Net;
class getIP
{

static void Main(string[] args) {
string machine_name = Dns.GetHostName();
IPHostEntry host = Dns.GetHostEntry(machine_name);

for (int i=0; i < host.AddressList.Length; i++){
Console.WriteLine(host.AddressList[i]);
}
Console.ReadLine();
}

}

the first ip is of the ethernet Local Area Network... the 2nd or the 3rd one are probably the external ip.

No comments:

Post a Comment