0

Why would one use {1,3} in \d{1,3} when catching an IP with grep? For example:

grep -Po 'inet addr:\K(?!127\.)\d{1,3}.\d{1,3}\.\d{1,3}\.\d{1,3}'

\K removes inet addr:, and (?!127\.), AFAIU, removes any address that starts with 127 (the loopback in that case), but what are the {1,3} after \d?

Clearly, we don't only want IP calsses that starts in 1 and end with 2 or 3 so the purpose there is unclear to me.

Note: inet addr: is part of the ifconfig Linux utility.

Osi
  • 1
  • 3
  • 9
  • 30

2 Answers2

0

While writing the question I figured out the purpose: It means that in each class of the 4 classes, we will have not more than 3 digits.

Indeed in IPv4 (I don't know about IPv6) we have only 3 digits in each class.

Osi
  • 1
  • 3
  • 9
  • 30
0

You have answered your question yourself however note that for general IPv4 the regex that should be used is the following:

'\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b'
                         ^^^^^^^^^^^^^^^^

that you could adapt to remove the localhost one.

In your case, the grep will also fetch chains of digits that are not proper IPs (e.g. integers > 255)

Allan
  • 12,117
  • 3
  • 27
  • 51
  • If we ought to match both IP and IP-like data streams, than yes, indeed the way you present is more careful, but the original IP I meant to match ([as you could see in this session](https://stackoverflow.com/questions/47784982/regex-grep-external-ip-brings-back-internal-ip-as-well-why/47790733#47790733)) is surly an IP address (the external IP of the VPS environment), supplied by the Linux `infconfig` utility. – Osi Dec 14 '17 at 04:00
  • I thumbed up your answer for noting this important data. – Osi Dec 14 '17 at 04:02
  • 1
    Depending on the data you're matching on, you may wantto be more or less strict. In the strictest sense, this too accepts many addresses which are not valid live public IP addresses (IANA reserved, broadcast addresses, .0 selects an entire network, etc). For parsing `ifconfig` output, those are lnlikely to occur, so even a much more relaxed regex will work fine and never produce any false positives. – tripleee Dec 19 '17 at 11:27