0

im having a hard time trying to create and find a good ipv4 regex match but all i can find is this:

(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})

does this regex combination match to something like xxx.xxx.xxx.xxx or xx.xxx.x.x etc? I'm trying to make a connection to a web server by pinging via domain name to get the ip but when i try it, the code returns that there is not match. here is the ping command btw:

PING google.com (172.217.1.14): 56 data bytes 
  • `{1,3}` means to match between 1 and 3 instances of the previous pattern. So `\d{1,3}` will match `1`, `12`, or `123`. – Barmar Aug 20 '21 at 00:16
  • What regexp engine are you using? If you're using basic regular expressions, it doesn't recognize the `\d` escape sequence. Use `[0-9]` instead. – Barmar Aug 20 '21 at 00:19
  • Barmar, isnt {1,3} a quantifier? –  Aug 20 '21 at 00:20
  • Yes. A quantifier is used to specify how many of the previous pattern to match. – Barmar Aug 20 '21 at 00:20
  • i thought it would do something like count anything like xxx.xxx.xx.xxx or x.xx.x.x –  Aug 20 '21 at 00:23
  • It will, since there are between 1 and 3 digits in each segment of the address. – Barmar Aug 20 '21 at 00:24
  • But you need to replace `\d` with `[0-9]` to match digits. – Barmar Aug 20 '21 at 00:24
  • okay, i was confused for a second. sorry about that –  Aug 20 '21 at 00:24
  • it still doesnt work when i change \d to [0-9] –  Aug 20 '21 at 00:25
  • You might need to select extended regular expression to get `{1,3}` quantifiers. – Barmar Aug 20 '21 at 00:27
  • Or you can install the PCRE library and use your original regexp. – Barmar Aug 20 '21 at 00:28
  • If using basic REs, the curly braces have to be escaped: `[0-9]\{1,3\}` – Shawn Aug 20 '21 at 01:14
  • However, this will match things like 999.999.999.999 that aren't valid IP addresses. You might consider using `inet_aton()` or something for further validation if that's important to catch. – Shawn Aug 20 '21 at 01:16
  • But this seems like it might be an XY problem. If you want to resolve a hostname to an IP address, use `getaddrinfo()`! – Shawn Aug 20 '21 at 01:18

1 Answers1

0

256.1.1.1 9.900.0.0 etc. are not valid, this parses those out w/o back-tracking (to prevent RE-DoS):

egrep '^((0|1[0-9]{0,2}|2([0-4][0-9]{0,1}|5[0-5]{0,1}|[6-9]){0,1}|[3-9][0-9]{0,1})\.){3}(0|1[0-9]{0,2}|2([0-4][0-9]{0,1}|5[0-5]{0,1}|[6-9]){0,1}|[3-9][0-9]{0,1})$'
Andrew
  • 1
  • 4
  • 19