There are various ways to check if an IP address is IPv4 or IPv6. 

Example 1: Using IPAddress.TryParse() Method
Example 2: Using Regex
Example 3: UsingSystem.Net.IpAddress

 

System.Net.IpAddress can be used to check whether it is IPV4 or IPV6 address.

Add Namespaces

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

 

use IPAddress.Parse(ipv6address)

var ipv6address = this._httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

var headers = this._httpContextAccessor.HttpContext.Request.Headers;

if (headers.ContainsKey("X-Forwarded-For"))
{
    ipv6address = headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0];
}

ipv6address = headers["CF-Connecting-IP"].ToString();

IPAddress address = IPAddress.Parse(ipv6address); /* https://learn.microsoft.com/en-us/dotnet/api/system.net.ipaddress.isloopback?view=net-8.0 */

var isipv6address = false;

if (address.AddressFamily == AddressFamily.InterNetworkV6)
    isipv6address = true;
else
   if (IPAddress.IsLoopback(address) && address.AddressFamily == AddressFamily.InterNetwork)
    isipv6address = false;

source:https://learn.microsoft.com/en-us/dotnet/api/system.net.ipaddress.isloopback?view=net-8.0

 

useful links

https://www.tutorialsrack.com/articles/413/how-to-check-if-a-given-ip-address-is-ipv4-or-ipv6-in-csharp

Comments


Comments are closed