4 ms·
Well, I mean, yes, those are all mistakes people are going to make, no doubt about that. But somehow the solution is missing? The core mistake here is using st
by zAy0LfpBZLC8mAC 8y ago
Well, I mean, yes, those are all mistakes people are going to make, no doubt about that. But somehow the solution is missing?
The core mistake here is using string manipulation at all. The only correct way to handle string data is to parse it, and then either operate on the parsed data structure, or re-serialize into a canonical format and use that for comparisons and stuff.
And in the best case, you don't try to build your own parser, but use a well-tested one that's already there. For the particular use case of parsing IP addresses, it's probably best to use getaddrinfo() with AI_NUMERICHOST, and for re-serialization getnameinfo() with the same flag. If those don't understand the address, you most likely won't be able to connect anyway. And they will handle stuff like link-local addresses correctly, at least as long as you are on the host that actually has the respective interface.
For databases, you use column types intended for storing IP addresses, so the database will do the parsing and canonicalization for you.
And when you actually have to build a parser yourself, read the damn spec for the format instead of going by what you think the format is, because most likely it's not that.
And mind you that most of those problems are not really IPv6-specific. There are also many ways to write an IPv4 address that your average parser will understand. Most of those are generally frowned upon, so they don't occur often, but if you want to reliably compare IPv4 addresses, you actually need to do the same as for IPv6.
- TorKlingberg 8y agoOne reason people keep using string manipulation is that in C getaddrinfo gives a addrinfo, which is quite a complex struct. It contains a struct sockaddr, which is actually a sockaddr_in, which contains both an address and a port. So now you have to carefully keep track of which of your addrinfos and sockaddrs have the port in them and which are just the address.