Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the port from a IP string that is IPv6 safe in C#

I need the IP without port on users that make requests in a rest API running on ASP.NET MVC. It seems the way to get the address is a combination of these:

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
HttpContext.Current.Request.UserHostAddress;

Which give me a string with IP:Port

IPV4 is simple, but from reading I expect IPV6 will give me something like this:

[1fff:0:a88:85a3::ac1f]:8001

IPAddress.Parse can handle IPv6 with port but not IPv4 with port which is strange.

I could inspect the string to see what kind of address it is, but I feel like there should be a better way.

Any ideas?

like image 411
Spencer Rose Avatar asked Jul 21 '15 08:07

Spencer Rose


1 Answers

Here is my makeshift version in the mean time

public string StripPortFromEndPoint(string endPoint)
{
    var splitList = endPoint.Split(':');
    if (splitList.Length > 2)
    {
        endPoint = IPAddress.Parse(endPoint).ToString();
    }
    else if (splitList.Length == 2)
    {
        endPoint = splitList[0];
    }
    else
    {
        throw new ParseException("No port separator found",0);
    }

    return endPoint;
}
like image 63
Spencer Rose Avatar answered Sep 28 '22 18:09

Spencer Rose