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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With