this post was submitted on 15 Nov 2023
942 points (95.7% liked)

Programmer Humor

25699 readers
1235 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 2 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] dannym@lemmy.escapebigtech.info 76 points 2 years ago* (last edited 2 years ago) (1 children)

Please don't. Use regex to find something that looks like an IP then build a real parser. This is madness, its's extremely hard to read and a mistake is almost impossible to spot. Not to mention that it's slow.

Just parse [0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3} using regex (for v4) and then have some code check that all the octets are valid (and store the IP as a u32).

[–] Emma_Gold_Man@lemmy.dbzer0.com 8 points 2 years ago (1 children)

And dupe check. 0.0.0.0 and 000.000.000.000 may both be valid, but they resolve the same

[–] dannym@lemmy.escapebigtech.info 3 points 2 years ago* (last edited 2 years ago) (2 children)

Definitely, tho if you store it as a u32 that is fixed magically. Because 1.2.3.4 and 1.02.003.04 both map to the same number.

What I mean by storing it as a u32 is to convert it to a number, similar to how the IP gets sent over the wire, so for v4:

octet[3] | octet[2] << 8 | octet[1] << 16 | octet[0] << 24

or in more human terms:

(fourth octet) + (third octet * 256) + (second octet * 256^2) + (first octet * 256^3)
[–] Emma_Gold_Man@lemmy.dbzer0.com 2 points 2 years ago

True enough for database or dictionary storage, but a lot of times things get implemented in arrays where you still wind up with two copies of the same uint32.