How to obtain the IP address of the interface...

G

Guest

How to obtain the IP address of the interface that is connected to the
Internet?
I´m using the code below to get IP address of the local machine:
//*********************************************
private void button1_Click(object sender, System.EventArgs e)
{
string HostName = Dns.GetHostName();
lblHostName.Text=HostName;
IPHostEntry ipEntry = Dns.GetHostByName (HostName);
IPAddress [] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
if(ipEntry.AddressList.AddressFamily
listBox1.Items.Add("IP:"+ i.ToString() + " " + addr.ToString ());
}
}
//*********************************************
The code is fine, but when I run the program, I receive a list of various
IPs due to the interfaces that Ihave on this machines. I know what is the
address that I´m using to connect to the Internet, but how to do this using
code? It is always the last addres on the list?
Thanks in advance,
Rodrigo
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

I think that you should get the default gateway, how to get it from code I
have no idea really. if you have more than one ip or interface it could be
any.

AFAIK there is no way to get or interact with the routing from .NET , I
would bet for WMI for this.

cheers,
 
W

Willy Denoyette [MVP]

Rodrigo C. Souza said:
How to obtain the IP address of the interface that is connected to the
Internet?
I´m using the code below to get IP address of the local machine:
//*********************************************
private void button1_Click(object sender, System.EventArgs e)
{
string HostName = Dns.GetHostName();
lblHostName.Text=HostName;
IPHostEntry ipEntry = Dns.GetHostByName (HostName);
IPAddress [] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
if(ipEntry.AddressList.AddressFamily
listBox1.Items.Add("IP:"+ i.ToString() + " " + addr.ToString ());
}
}
//*********************************************
The code is fine, but when I run the program, I receive a list of various
IPs due to the interfaces that Ihave on this machines. I know what is the
address that I´m using to connect to the Internet, but how to do this
using
code? It is always the last addres on the list?
Thanks in advance,
Rodrigo


You can use System.Management classes and WMI for this.

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top