Sammy Ageil

Lead by example

Get all IP Addresses in .Net

April 09
by Sammy Ageil 9. April 2011 06:02

For licensing reasons, we needed to get all of the IPV4 IP Addresses of the server hosting one of our products.
The major question I had to answer what if the server is configured using IPV6?
Here is what I came up to solve this issue.
I hope it help someone else the time to resolve this issue.

First add the following namespaces

using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;

Code

var ipv4 = NetworkInterface
           .GetAllNetworkInterfaces()
           .SelectMany(ni => ni.GetIPProperties().UnicastAddresses.Where(nip => nip.IPv4Mask != null && nip.Address.AddressFamily== AddressFamily.InterNetwork ).Select(ip => ip.Address.ToString())).ToArray();

            var ipv6 = NetworkInterface
           .GetAllNetworkInterfaces()
           .SelectMany(ni => ni.GetIPProperties().UnicastAddresses.Where(nip => nip.Address.AddressFamily == AddressFamily.InterNetworkV6).Select(ip => ip.Address.ToString())).ToArray();

            var allIPS = NetworkInterface
            .GetAllNetworkInterfaces()
            .SelectMany(ni => ni.GetIPProperties().UnicastAddresses.Where(nip =>  nip.Address.AddressFamily == AddressFamily.InterNetwork || nip.Address.AddressFamily == AddressFamily.InterNetworkV6).Select(ip => ip.Address.ToString())).ToArray();

VS.NET version

Imports

Imports System.Net
Imports System.Net.Sockets
Imports System.Net.NetworkInformation
Code
Dim ipv4 = NetworkInterface.GetAllNetworkInterfaces().SelectMany(Function(ni) ni.GetIPProperties().UnicastAddresses.Where(Function(nip) nip.IPv4Mask IsNot Nothing AndAlso nip.Address.AddressFamily = AddressFamily.InterNetwork).[Select](Function(ip) ip.Address.ToString())).ToArray()

Dim ipv6 = NetworkInterface.GetAllNetworkInterfaces().SelectMany(Function(ni) ni.GetIPProperties().UnicastAddresses.Where(Function(nip) nip.Address.AddressFamily = AddressFamily.InterNetworkV6).[Select](Function(ip) ip.Address.ToString())).ToArray()

Dim allIPS = NetworkInterface.GetAllNetworkInterfaces().SelectMany(Function(ni) ni.GetIPProperties().UnicastAddresses.Where(Function(nip) nip.Address.AddressFamily = AddressFamily.InterNetwork OrElse nip.Address.AddressFamily = AddressFamily.InterNetworkV6).[Select](Function(ip) ip.Address.ToString())).ToArray()
 

Enjoy

Tags: , , , ,