1

I need to save the IP addresses of my users to uniquely identify them - I want to avoid using an account system. According to the answer to this question, I need to use Request.UserHostAddress.

However, I want to save the IP addresses not as strings but as integers. I already created a function to convert regular IPv4 addresses to their numeric equivalent. What kind of formats (as strings) can I expect to get from Request.UserHostAddress? I want to expand my function to deal with IPv6 addresses, too, but I want to know the different kinds of formats I could get out of Request.UserHostAddress, especially considering how you can shorten IPv6 addresses.

noClue
  • 958
  • 1
  • 13
  • 34
  • Rather than parsing it on your own, have you considered using an out-of-the-box [IPAddress class](https://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse(v=vs.110).aspx) for this? – Andrei Aug 08 '18 at 15:47
  • @Andrei =O Now I feel like an idiot, how did I never find this? Should've used "parser" in my searches instead of "ip address to number"... Yeah, I guess if I can get the numeric value out of it after turning it into an IPAddress instance, then you pretty much answered my question. Add it as an answer if you want. – noClue Aug 08 '18 at 15:52

1 Answers1

1

Rather than worrying about specific formats this property may throw at you, consider using an IP wrapper class that is shipped in System.Net: IPAddress.

It provides static Parse(string) method that handles both IPv4 and IPv6. It also can give you the address as an array of bytes with GetAddressBytes(), which you can convert to a numerical value as needed (here is a code sample of how to do it).

Andrei
  • 55,890
  • 9
  • 87
  • 108