user3015248
user3015248

Reputation: 89

Get IP from host in C#

hi i am wanting to get the ip of a host, the code I found is this:

    string howtogeek = "www.google.com";
    IPAddress[] addresslist = Dns.GetHostAddresses(howtogeek);
    foreach (IPAddress theaddress in addresslist)
    {
        test.AppendText(theaddress.ToString() + Environment.NewLine);
    }

the problem is that I only get the first IP found without using foreach because I just want the first one, anyone can help me?

Upvotes: 0

Views: 466

Answers (3)

Mark Arnott
Mark Arnott

Reputation: 1994

The first IP address will be

string howtogeek = "www.google.com";
IPAddress[] addresslist = Dns.GetHostAddresses(howtogeek);
IPAddress firstAddress = addresslist[0];

Upvotes: 0

Oscar
Oscar

Reputation: 13960

Normally a machine can have multiple ip addresses. If there is only one network adapter XX there will be at least two ip's: the network adapter XX ip and the loopback 127.0.0.1. That say, you can use the following code to get the first IP:

string howtogeek = "www.google.com";
IPAddress[] addresslist = Dns.GetHostAddresses(howtogeek);
if(addresslist.Lengt > 0){
   test.AppendText(addresslist[0].ToString() + Environment.NewLine);
}

Upvotes: 0

Christian Phillips
Christian Phillips

Reputation: 18749

You could just use:

string howtogeek = "www.google.com";
IPAddress[] addresslist = Dns.GetHostAddresses(howtogeek);
var firstIp = addresslist[0]; 

Depending on the framework you are using, you can also use Enumerable.FirstOrDefault().

string howtogeek = "www.google.com";
IPAddress[] addresslist = Dns.GetHostAddresses(howtogeek);
var firstIp = addresslist.FirstOrDefault(); 

Upvotes: 3

Related Questions