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

  • Thread starter Thread starter Guest
  • Start date Start date
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
 
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,
 
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.
 
Back
Top