Canonicalize CIDR: Difference between revisions
Content added Content deleted
(→{{header|TXR}}: Take advantage of that inaddr-str already canonicalizes the numeric address.) |
(→{{header|TXR}}: Remove the solution which wastefully does the bit stripping that naddr-str already performed.) |
||
Line 1,748: | Line 1,748: | ||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
The <code>inaddr-str</code> function in TXR Lisp parses IPv4 addresses, converting them to a <code>sockaddr-in</code> structure. If there is a slash notation present, it is recognized. The prefix value is validated and stored in the structure as the <code>prefix</code> value, and the numeric address is canonicalized to clear the irrelevant bits. Thus, the solution looks like this: |
|||
The following is a wasteful method which fails to take into account that <code>inaddr-str</code> is already stripping the bits: |
|||
<syntaxhighlight lang="txrlisp">(defun cidr-canon (str) |
|||
(match `@dots/@bits` str |
|||
(let ((inaddr (inaddr-str dots).addr) |
|||
(bits (int-str bits))) |
|||
`@(str-inaddr (logand inaddr (ash -1 (- 32 bits))))/@bits`)))</syntaxhighlight> |
|||
The following is a shorter method: |
|||
<syntaxhighlight lang="txrlisp">(defun cidr-canon (str) |
<syntaxhighlight lang="txrlisp">(defun cidr-canon (str) |
||
Line 1,762: | Line 1,754: | ||
`@(str-inaddr a.addr)/@{a.prefix}`))</syntaxhighlight> |
`@(str-inaddr a.addr)/@{a.prefix}`))</syntaxhighlight> |
||
Furthermore, the prefix notation can be condensed by removing unnecessary zeros. That is to say, <code>10.1.2.3/16</code> can be not just canonicalized to strip the irrelevant bits, but then shortened to <code>10.1/16</code>. |
|||
The built-in function <code>inaddr-str-net</code> will produce this condensed prefix notation: |
The built-in function <code>inaddr-str-net</code> will produce this condensed prefix notation: |