0

I use this type of code to get my systems IPv4 address:

string ipadress = Dns.GetHostEntry(Dns.GetHostName())
.AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork)
.ToString();
System.Windows.Forms.MessageBox.Show(ipadress);

But as I have more than 1 network interface, the result might not be what I need. Can I search for the interface which IP begins with "10."? That would be what I need. Just the IP address of interface within network 10....

:)

1
  • What data does AddressList give you? Commented Dec 9, 2022 at 15:34

1 Answer 1

2

You could use a Linq query to look for an IP that starts with a certain pattern perhaps.

var ipAddress = Dns.GetHostEntry(Dns.GetHostName())
                .AddressList
                .Where(addr => addr.ToString().StartsWith("10."));

foreach (var ipAddress in ipAddresses)
{
    Console.WriteLine(ipAddress.ToString());
}

EDIT - If you only want to get 1 item you can replace the Where query with FirstOrDefault, which tries to match the condition of the query, and will return the first item it find. If it can't find anything that matches the condition, it will return the default value of the return type, in this case IPAddress

var ipAddress = Dns.GetHostEntry(Dns.GetHostName())
                .AddressList
                .FirstOrDefault(addr => addr.ToString().StartsWith("10."));
Sign up to request clarification or add additional context in comments.

4 Comments

Just as a precaution, might want to StartsWith("10."), just in case an IP starts with 100 through 109.
Thanks @gunr2171 - For the sake of the question that was asked, I've updated my answer to include the .
Thank you very much for this answer. But visual studio tells me that this property is deprecated. When I run it anyway, the output is: System.Linq.Enumerable+WhereArrayIterator´1[System.Net.IPAddress]
@itsenaf that's because a Where in Linq returns an IEnumerable rather than an individual object, as there may be 0 or more results. I've updated the original solution, adding a loop to loop through the results that are returned and removing the deprecated issues. I've also added anther solution using FirstOrDefault which may be more what you're looking for. See the explanation above in the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.