9. April 2011
Sammy Ageil
C#
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 is, 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;
C# 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();
VB.NET version:
Imports
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports System.Net
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()