I am trying to parse a string of an ip-address to a System.Net.IPAddress.
var ip = IPAddress.Parse(iPAddressDefinition);
The string can be every IPv4 or every IPv6 address, i.e. 0.0.0.0 - 255.255.255.255 and :: - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff. Parsing works 99% of the time as intended.
However if the third (from the right) octet is a ffff, e.g. ::ffff:0808:0808, the Parse() function interprets the string as an IPv4-mapped-to-IPv6 address, leading to errors later in the code.
The result for the example above is ::ffff.8.8.8.8, but ::ffff:808:808 or ::ffff:0808:0808 is what I would like to receive.
Is there a simple, error-free way with built-in function to achieve this or do I have to write a string manipulation function?
Edit: After reading the helpful comments, I realized, that this is not a .Parse() -Problem but a .toString() - Problem
I found a solution that works for me. If you find a better solution, please let me know!
After reading the helpful comments, I realized, that this is not a .Parse() -Problem but a .toString() - Problem.
var ip = IPAddress.Parse(iPAddressDefinition);
if (ip.IsIPv4MappedToIPv6)
{
var index = iPAddressDefinition.IndexOf("ffff");
strIp = string.Concat("::", iPAddressDefinition[index..]);
}
else
{
strIp = ip.ToString();
}
If you find a better solution, please let me know!