init
Some checks are pending
CI / build (push) Waiting to run
CI / deploy (push) Blocked by required conditions

This commit is contained in:
ge 2025-04-05 22:49:43 +03:00
commit ef87b21308
21 changed files with 4262 additions and 0 deletions

8
.editorconfig Normal file
View File

@ -0,0 +1,8 @@
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.v]
indent_style = tab

7
.gitattributes vendored Normal file
View File

@ -0,0 +1,7 @@
* text=auto eol=lf
*.bat eol=crlf
**/*.v linguist-language=V
**/*.vv linguist-language=V
**/*.vsh linguist-language=V
**/v.mod linguist-language=V

53
.github/workflows/ci.yaml vendored Normal file
View File

@ -0,0 +1,53 @@
name: CI
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup V
run: |
wget -qO /tmp/v.zip https://github.com/vlang/v/releases/latest/download/v_linux.zip
unzip -q /tmp/v.zip -d /tmp
echo /tmp/v >> "$GITHUB_PATH"
- name: Run tests
run: v -stats test .
- name: Build docs
run: |
v doc -f html -m .
pushd _docs
ln -vs netaddr.html index.html
ls -alFh
popd
- name: Upload static files as artifact
id: deployment
uses: actions/upload-pages-artifact@v3
with:
path: _docs/
deploy:
needs: build
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
permissions:
contents: read
pages: write
id-token: write

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Binaries for programs and plugins
main
ipaddr
*.exe
*.exe~
*.so
*.dylib
*.dll
# Ignore binary output folders
bin/
# Ignore common editor/system specific metadata
.DS_Store
.idea/
.vscode/
*.iml
# ENV
.env
# other
/doc
*.todo

674
COPYING Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

165
COPYING.LESSER Normal file
View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

26
Makefile Normal file
View File

@ -0,0 +1,26 @@
SRC_DIR ?= src
DOC_DIR ?= doc
TESTS_DIR ?= tests
all: fmt vet missdoc test
fmt:
v fmt -verify -diff $(SRC_DIR)
vet:
v vet -W -r -I -F $(SRC_DIR)
missdoc:
v missdoc -r --verify $(SRC_DIR)
test:
v test .
doc:
v doc -f html -m . -o $(DOC_DIR)
clean:
rm -r $(DOC_DIR) || true
serve: clean doc
v -e "import net.http.file; file.serve(folder: '$(DOC_DIR)')"

267
README.md Normal file
View File

@ -0,0 +1,267 @@
# Network address processing library for V
`netaddr` supports IP (both IPv4 and IPv6) and EUI (EUI-48, EUI-64) addresses.
Features:
- Parsing and validation of EUI, IP addresses and IP network addresses.
- Converting addresses to/from different formats, e.g. various string representations, byte arrays, integers.
- IP addresses and networks comparison.
- IPv4-IPv6 interoperability.
- IPv6 scopes support.
- Parsing/creating Teredo (IPv4 over IPv6 tunneling) addresses.
- Testing addresses and networks i.e. check is network intended for private use or not and many other tests.
- Generating random EUI-48 (useful for virtual machines, etc).
- Converting EUI to IPv6.
- Calculating IP networks (both versions).
- ...
## Usage
### IP address/network parsing and validation
Once you got an `Ipv{4,6}Addr` or `Ipv{4,6}Net` instance without errors — that's done,
validation is passed. In the simplest case you can do:
```v okfmt
if ip := netaddr.IpAddr.from_string('::1') {
// address is valid
} else {
// address is not valid
}
```
More concrete example that prints the address on success:
```v
import netaddr
fn main() {
addr := arguments()[1] or {
panic('no such argument, specify an IP address')
}
ip := netaddr.IpAddr.from_string(addr) or {
panic('${addr} is not valid IP address')
}
if ip is netaddr.Ipv4Net || ip is netaddr.Ipv6Net {
panic('${ip} seems to be network, not a single host addresses')
}
println(addr)
}
```
### Working with IP networks
Basic usage:
```v
import netaddr
fn main() {
network4 := netaddr.Ipv4Net.from_string('172.16.16.0/24')!
network6 := netaddr.Ipv6Net.from_string('fe80:aaaa:bbbb:cccc::/64')!
println(network4)
println(network6)
}
```
The `from_string()` method of the Ipv4Net and Ipv6Net structs supports several different
formats for network prefixes:
- a single address without a prefix length will be considered as a network with a prefix of 32 or 128 depending on the IP version;
- an address with an integer non-negative prefix length;
- an address with a subnet mask;
- an address with a host mask;
```v okfmt
network := netaddr.Ipv4Net.from_string('203.0.113.99/0.0.0.255')!
assert network.network_address.str() == '203.0.113.0'
assert (network.host_address as netaddr.Ipv4Addr).str() == '203.0.113.99'
```
If host bits is set in the network address the optional `host_address` field will be filled with
this host address. The `network_address` field always will contain the real network address.
The `host_address` will equal `none` for single address "networks" such as `127.0.0.1/32`, etc.
#### Iterating over network hosts
`Ipv4Net` and `Ipv6Net` has `next()` method that implements the V iterator mechanism
which allow you use object in `for` loop in following maner:
```v okfmt
network := netaddr.Ipv4Net.from_string('172.16.16.0/26')!
for host in network {
// `host` is an Ipv4Addr instance
if host == network.network_address || host == network.broadcast_address {
continue
}
println(host)
}
```
Note that the iterator will iterate over all addresses in the network, including those that
cannot be used as a host address: the network address and broadcast address. Exceptions are
the networks with small prefixes: 31 (point-to-point) and 32 (single address) for IPv4, and
127 and 128 for IPv6 respectively.
If you just want to check is network contain some address use `contains()` method:
```v okfmt
network := netaddr.Ipv4Net.from_string('172.16.0.0/26')!
addr := netaddr.Ipv4Addr.from_string('172.16.16.68')!
assert !network.contains(addr)
```
#### Networks intersection tests and subnetting
To choose the right prefix when planning a network, it is important to avoid overlapping
network address spaces.
Check partial overlapping:
```v okfmt
net_a := netaddr.Ipv4Net.from_string('100.64.0.0/22')!
net_b := netaddr.Ipv4Net.from_string('100.64.4.0/22')!
assert !net_a.overlaps(net_b)
```
Also you can check is the network a subnet or supernet of another one:
```v okfmt
assert !net_a.is_subnet_of(net_b)
assert !net_a.is_supernet_of(net_b)
```
To split the network into equal prefixes, you can use the `subnets()` method:
```v okfmt
network := netaddr.Ipv4Net.from_string('100.64.64.0/20')!
println(network)
mut subnets := []netaddr.Ipv4Net{}
for subnet in network.subnets(22)! {
subnets << subnet
}
println(subnets)
// [100.64.64.0/22, 100.64.68.0/22, 100.64.72.0/22, 100.64.76.0/22]
```
### IPv4-IPv6 interoperability
`netaddr` supports IP conversion between 4 and 6 versions in both directions.
The V REPL session below illustrates this:
```
>>> import netaddr
>>> ip4 := netaddr.Ipv4Addr.from_string('203.0.113.99')!
>>> ip4
203.0.113.99
>>> ip6 := ip4.ipv6()
>>> ip6
::ffff:203.0.113.99
>>> ip6.is_ipv4_mapped()
true
>>> ip6.is_ipv4_compat()
false
>>> ip6.ipv4()!
203.0.113.99
>>> ip4 == ip6.ipv4()!
true
```
IPv6 address cannot be converted to IPv4 if it is not the IPv4-mapped or IPv4-compatible
per RFC 4291 Section 2.5.5.
Also several representation formats are supported:
```
>>> ip6.format(.dotted | .compact)
::ffff:203.0.113.99
>>> ip6.format(.dotted | .verbose)
0000:0000:0000:0000:0000:ffff:203.0.113.99
>>> ip6.format(.compact)
::ffff:cb00:7163
>>> ip6.format(.verbose)
0000:0000:0000:0000:0000:ffff:cb00:7163
```
### Dealing with scoped IPv6 addresses
`Ipv6Addr` struct has optional `zone_id` field that contains the scope zone identifier
if available. For example (V REPL session):
```
>>> ip6_scoped := netaddr.Ipv6Addr.from_string('fe80::d08e:6658:38bd:6391%wlan0')!
>>> ip6_scoped
fe80::d08e:6658:38bd:6391%wlan0
>>> ip6_scoped.zone_id
Option('wlan0')
>>> zone_id := ip6_scoped.zone_id as string
>>> zone_id
wlan0
```
For creating scoped address from `big.Integer`, `u8`, `u16`, etc use the optional `zone_id`
parameter. e.g.:
```v okfmt
// vfmt off
new := netaddr.Ipv6Addr.new(
0xfe80, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1234,
zone_id: 'eth0'
)!
from_u8 := netaddr.Ipv6Addr.from_octets(
[
u8(0xfe), 0x80,
0x0, 0x0,
0x0, 0x0,
0x0, 0x0,
0x0, 0x0,
0x0, 0x0,
0x0, 0x0,
0x12, 0x34
]!,
zone_id: 'eth0'
)!
// vfmt on
println(new) // fe80::1234%eth0
println(from_u8) // fe80::1234%eth0
```
Also you can create new IPv6 address with zone_id from existing `Ipv6Addr` instance:
```
>>> ip6 := netaddr.Ipv6Addr.from_string('fe80::d08e:6658:38bd:6391')!
>>> new_ip6 := ip6.with_scope('eth1')!
>>> new_ip6
fe80::d08e:6658:38bd:6391%eth1
```
Scoped IPv6 networks are supported, but `Ipv6Net` struct does not have own `zone_id`
field, refer to it's `network_address` as follows:
```
>>> ip6net := netaddr.Ipv6Net.from_string('fe80::%eth1/64')!
>>> ip6net
fe80::%eth1/64
>>> ip6net.network_address.zone_id
Option('eth1')
```
### Getting global unicast IPv6 from EUI-48
This is a slightly synthetic example that shows how you can automatically get a global
unicast IPv6 address for a host given the network prefix.
```v okfmt
// Known network prefix
network := netaddr.Ipv6Net.from_string('2001:0db8::/64')!
// Lets generate random EUI-48
eui := netaddr.Eui48.random()
// ipv6() method converts EUI-48 to Modified EUI-64 and appends it to prefix per RFC 4291
ip := eui.ipv6(network.network_address)!
println(ip) // 2001:db8::8429:6bff:fedc:ef8b
```
Note that using EUI in IPv6 address may cause security issues. See
[RFC 4941](https://datatracker.ietf.org/doc/html/rfc4941) for details.

134
src/128bit_math.v Normal file
View File

@ -0,0 +1,134 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
/*
This file contains functions for operating with big endian ordered byte arrays.
Using big.Integer is significantly slower than doing math strictly on 128-bit
numbers. At a minimum, you have to do expensive instantiation of big.Integer.
The functions below do not require copying arrays and allocate less memory.
Functions missing:
fn add_128(a [16]u8, b [16]u8) [16]u8
fn diff_128(a [16]u8, b [16]u8) [16]u8
*/
module netaddr
import math.bits
const max_128 = [16]u8{init: 0xff}
@[direct_array_access; inline]
fn bit_len_128(a [16]u8) int {
if a == [16]u8{} {
return 0
}
mut len := 128
mut zeros := 0
for i in 0 .. 16 {
zeros = bits.leading_zeros_8(a[i])
if zeros == 0 {
break
}
len -= zeros
}
return len
}
@[direct_array_access; inline]
fn left_shift_128(a [16]u8, shift int) [16]u8 {
mut res := [16]u8{}
shift_mod := shift % 8
mask := u8((1 << shift_mod) - 1)
offset := shift / 8
for i := 0; i < 16; i++ {
src_idx := i + offset
if src_idx >= 16 {
res[i] = 0
} else {
mut dst := u8(a[i] << shift_mod)
if src_idx + 1 < 16 {
dst |= a[src_idx + 1] >> ((8 - shift_mod) & mask)
}
res[i] = dst
}
}
return res
}
@[direct_array_access; inline]
fn right_shift_128(a [16]u8, shift int) [16]u8 {
mut res := [16]u8{}
shift_mod := shift % 8
mask := u8(0xff) << (8 - shift_mod)
offset := shift / 8
for i := 15; i >= 0; i-- {
src_idx := i - offset
if src_idx < 0 {
res[i] = 0
} else {
mut dst := (u8(0xff) & a[i]) >> shift_mod
if src_idx - 1 >= 0 {
dst |= a[src_idx - 1] << ((8 - shift_mod) & mask)
}
res[i] = dst
}
}
return res
}
@[direct_array_access; inline]
fn bitwise_and_128(a [16]u8, b [16]u8) [16]u8 {
mut res := [16]u8{}
for i := 0; i < 16; i++ {
res[i] = a[i] & b[i]
}
return res
}
@[direct_array_access; inline]
fn bitwise_or_128(a [16]u8, b [16]u8) [16]u8 {
mut res := [16]u8{}
for i := 0; i < 16; i++ {
res[i] = a[i] | b[i]
}
return res
}
@[direct_array_access; inline]
fn bitwise_xor_128(a [16]u8, b [16]u8) [16]u8 {
mut res := [16]u8{}
for i := 0; i < 16; i++ {
res[i] = a[i] ^ b[i]
}
return res
}
// compare_128 returns:
//
// * -1 if a < b
// * 0 if a == b
// * +1 if a > b
@[direct_array_access; inline]
fn compare_128(a [16]u8, b [16]u8) int {
for i in 0 .. 16 {
if a[i] != b[i] {
return if a[i] < b[i] { -1 } else { 1 }
}
}
return 0
}

283
src/eui48.v Normal file
View File

@ -0,0 +1,283 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
import encoding.binary
import math.bits
import rand
import rand.wyrand
pub struct Eui48 {
addr [6]u8
}
// Eui48.new creates new EUI-48 from six octets.
pub fn Eui48.new(a u8, b u8, c u8, d u8, e u8, f u8) Eui48 {
return Eui48{
addr: [a, b, c, d, e, f]!
}
}
// Eui48.from_octets creates new EUI-48 from six-element byte array.
pub fn Eui48.from_octets(addr [6]u8) Eui48 {
return Eui48{addr}
}
// Eui48.from_string parses addr string and returns new EUI-48 instance.
// Example:
// ```
// assert Eui48.from_string('a96:7a87:4ae3')!.str() == '0a-96-7a-87-4a-e3'
// ```
pub fn Eui48.from_string(addr string) !Eui48 {
mut bytes := [6]u8{}
match true {
addr.contains_any('-:') {
// canonical and unix formats
mac := addr.split_any('-:')
if mac.len == 6 {
for i := 0; i < 6; i++ {
if !('0x' + mac[i]).is_hex() {
return error('invalid octet in ${addr}')
}
bytes[i] = ('0x' + mac[i]).u8()
}
} else {
return error('6 octets expected in ${addr}')
}
}
addr.contains('.') {
// cisco triple-hextet format
mac := addr.split('.')
if mac.len == 3 {
mut i := 0
for part in mac {
if !('0x' + part).is_hex() {
return error('non-hexadecimal value in ${addr}')
}
pair := ('0x' + part).u8_array()
bytes[i] = pair[0]
bytes[i + 1] = pair[1]
i += 2
}
} else {
return error('3 hextets expected in ${addr}')
}
}
('0x' + addr).is_hex() {
// bare hex digit
mac := ('0x' + addr).u8_array()
len_diff := 6 - mac.len
if len_diff == 0 {
for i := 0; i < 6; i++ {
bytes[i] = mac[i]
}
} else if len_diff > 0 {
mut i := 0
for pos in len_diff .. 6 {
bytes[pos] = mac[i]
i++
}
} else {
return error('6 octets expected in ${addr}')
}
}
else {
return error('invalid EUI-48 in ${addr}')
}
}
return Eui48{bytes}
}
// Eui48.random is guaranteed to return a locally administered unicast EUI-48.
// By default the WyRandRNG is used with default seed. You can set custom OUI
// if you don't want generate random one.
// Example:
// ```v ignore
// >>> netaddr.Eui48.random()
// be-8c-f7-90-b4-60
// >>> netaddr.Eui48.random(oui: [u8(0x02), 0x0, 0x0]!)
// 02-00-00-2d-1d-01
// ```
pub fn Eui48.random(params Eui48RandomParams) Eui48 {
mut eui := [6]u8{}
mut prng := params.prng
if params.seed.len > 0 {
prng.seed(params.seed)
}
if params.oui != none {
eui[0], eui[1], eui[2] = params.oui[0], params.oui[1], params.oui[2]
} else {
eui[0], eui[1], eui[2] = prng.u8(), prng.u8(), prng.u8()
if (eui[0] >> 1) & 1 == 0 {
eui[0] ^= 0x02 // ensure to address is locally administreted
}
if eui[0] & 1 != 0 {
eui[0] &= ~1 // ensure to address is unicast
}
}
eui[3], eui[4], eui[5] = prng.u8(), prng.u8(), prng.u8()
return Eui48{eui}
}
// str returns EUI-48 string representation in canonical format.
pub fn (e Eui48) str() string {
return e.format(.canonical)
}
// format returns the MAC address as a string formatted according to the fmt rule.
pub fn (e Eui48) format(fmt Eui48Format) string {
mut mac := []string{}
match fmt {
.canonical {
for b in e.addr {
mac << b.hex()
}
return mac.join('-')
}
.unix {
for b in e.addr {
mac << b.hex()
}
return mac.join(':')
}
.hextets {
for i := 0; i <= 4; i += 2 {
mac << e.addr[i..i + 2].hex()
}
return mac.join('.')
}
.bare {
return e.addr[..].hex()
}
}
}
// u8_array returns EUI-48 as byte array.
pub fn (e Eui48) u8_array() []u8 {
return e.addr[..]
}
// u8_array_fixed returns EUI-48 as fixed size byte array.
pub fn (e Eui48) u8_array_fixed() [6]u8 {
return e.addr
}
// bit_len returns number of bits required to represent the current EUI-48.
pub fn (e Eui48) bit_len() int {
return bits.len_64(binary.big_endian_u64(e.addr[..]))
}
// oui_bytes returns the 24 bit Organizationally Unique Identifier (OUI) as byte array.
pub fn (e Eui48) oui_bytes() [3]u8 {
return [e.addr[0], e.addr[1], e.addr[2]]!
}
// ei_bytes returns the 24 bit Extended Identifier (EI) as byte array.
pub fn (e Eui48) ei_bytes() [3]u8 {
return [e.addr[3], e.addr[4], e.addr[5]]!
}
// eui64 returns the EUI-64 converted from EUI-48 via extending address with FF-FE bytes.
pub fn (e Eui48) eui64() Eui64 {
return Eui64{
addr: [e.addr[0], e.addr[1], e.addr[2], 0xff, 0xfe, e.addr[3], e.addr[4], e.addr[5]]!
}
}
// modified_eui64 converts the EUI-48 to Modified EUI-64.
// This is the same as `eui64()`, but the U/L-bit (universal/local bit) is inverted.
pub fn (e Eui48) modified_eui64() Eui64 {
return Eui64{
addr: [(e.addr[0] ^ 0x02), e.addr[1], e.addr[2], 0xff, 0xfe, e.addr[3], e.addr[4], e.addr[5]]!
}
}
// ipv6 creates new IPv6 address from EUI-48. EUI-48 will be converted to
// Modified EUI-64 and appended to network prefix. Byte-reversed `prefix` must fit in 64 bit.
pub fn (e Eui48) ipv6(prefix Ipv6Addr) !Ipv6Addr {
pref := prefix.u8_array_fixed()
eui64 := e.modified_eui64().u8_array_fixed()
if pref[8..] == []u8{len: 8} {
return Ipv6Addr.from_octets([
pref[0],
pref[1],
pref[2],
pref[3],
pref[4],
pref[5],
pref[6],
pref[7],
eui64[0],
eui64[1],
eui64[2],
eui64[3],
eui64[4],
eui64[5],
eui64[6],
eui64[7],
]!)!
}
return error('The prefix ${prefix} is too long. ' +
'At least 64 bits must remain for the interface identifier.')
}
// ipv6_link_local returns link-local IPv6 address created from EUI-48.
pub fn (e Eui48) ipv6_link_local() Ipv6Addr {
return e.ipv6(Ipv6Addr.new(0xfe80, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000) or { Ipv6Addr{} }) or { Ipv6Addr{} }
}
// is_universal returns true if address is universally administreted.
pub fn (e Eui48) is_universal() bool {
// U/L bit is 0
return (e.addr[0] >> 1) & 1 == 0
}
// is_local returns true if address is locally administreted.
pub fn (e Eui48) is_local() bool {
return !e.is_universal()
}
// is_multicast returns true if address is multicast.
pub fn (e Eui48) is_multicast() bool {
return !e.is_unicast()
}
// is_unicast returns true if address is unicast.
pub fn (e Eui48) is_unicast() bool {
// I/G bit is 0
return e.addr[0] & 1 == 0
}
// == returns true if a is equals b.
pub fn (a Eui48) == (b Eui48) bool {
return a.addr == b.addr
}
@[params]
pub struct Eui48RandomParams {
pub:
oui ?[3]u8 // the custom OUI which is used instead of the random one.
seed []u32 // seed for PRNG
prng rand.PRNG = wyrand.WyRandRNG{}
}
pub enum Eui48Format {
canonical // e.g. 0a-96-7a-87-4a-e3
unix // e.g. 0a:96:7a:87:4a:e3
hextets // e.g. 0a96.7a87.4ae3
bare // e.g. 0a967a874ae3
}

240
src/eui64.v Normal file
View File

@ -0,0 +1,240 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
import encoding.binary
import math.bits
pub struct Eui64 {
addr [8]u8
}
// Eui64.new creates new EUI-64 from eigth octets.
pub fn Eui64.new(a u8, b u8, c u8, d u8, e u8, f u8, g u8, h u8) Eui64 {
return Eui64{
addr: [a, b, c, d, e, f, g, h]!
}
}
// Eui64.from_octets creates new EUI-64 from eight-element byte array.
pub fn Eui64.from_octets(addr [8]u8) Eui64 {
return Eui64{addr}
}
// Eui64.from_string parses addr string and returns new EUI-64 instance.
pub fn Eui64.from_string(addr string) !Eui64 {
mut bytes := [8]u8{}
match true {
addr.contains_any('-:') {
// canonical and colon-separated forms
mac := addr.split_any('-:')
if mac.len == 8 {
for i := 0; i < 8; i++ {
if !('0x' + mac[i]).is_hex() {
return error('invalid octet in ${addr}')
}
bytes[i] = ('0x' + mac[i]).u8()
}
} else {
return error('8 octets expected in ${addr}')
}
}
addr.contains('.') {
// period separated hextets
mac := addr.split('.')
if mac.len == 4 {
mut i := 0
for part in mac {
if !('0x' + part).is_hex() {
return error('non-hexadecimal value in ${addr}')
}
pair := ('0x' + part).u8_array()
bytes[i] = pair[0]
bytes[i + 1] = pair[1]
i += 2
}
} else {
return error('four hextets expected in ${addr}')
}
}
('0x' + addr).is_hex() {
// bare hex digit
mac := ('0x' + addr).u8_array()
len_diff := 8 - mac.len
if len_diff == 0 {
for i := 0; i < 8; i++ {
bytes[i] = mac[i]
}
} else if len_diff > 0 {
mut i := 0
for pos in len_diff .. 6 {
bytes[pos] = mac[i]
i++
}
} else {
return error('8 octets expected in ${addr}')
}
}
else {
return error('invalid EUI-64 in ${addr}')
}
}
return Eui64{bytes}
}
// str returns EUI-64 string representation in canonical format.
pub fn (e Eui64) str() string {
return e.format(.canonical)
}
// format returns the EUI-64 as a string formatted according to the fmt rule.
pub fn (e Eui64) format(fmt Eui64Format) string {
mut mac := []string{}
match fmt {
.canonical {
for b in e.addr {
mac << b.hex()
}
return mac.join('-')
}
.unix {
for b in e.addr {
mac << b.hex()
}
return mac.join(':')
}
.hextets {
for i := 0; i <= 6; i += 2 {
mac << e.addr[i..i + 2].hex()
}
return mac.join('.')
}
.bare {
return e.addr[..].hex()
}
}
}
// u8_array returns EUI-64 as byte array.
pub fn (e Eui64) u8_array() []u8 {
return e.addr[..]
}
// u8_array_fixed returns EUI-64 as fixed size byte array.
pub fn (e Eui64) u8_array_fixed() [8]u8 {
return e.addr
}
// bit_len returns number of bits required to represent the current EUI-64.
pub fn (e Eui64) bit_len() int {
return bits.len_64(binary.big_endian_u64(e.addr[..]))
}
// oui_bytes returns the 24 bit Organizationally Unique Identifier (OUI) as byte array.
pub fn (e Eui64) oui_bytes() [3]u8 {
return [e.addr[0], e.addr[1], e.addr[2]]!
}
// ei_bytes returns the 40 bit Extended Identifier (EI) as byte array.
pub fn (e Eui64) ei_bytes() [5]u8 {
return [e.addr[3], e.addr[4], e.addr[5], e.addr[6], e.addr[7]]!
}
// modified_eui64 returns the Modified EUI-64 Format Interface Identifier per RFC 4291 (Appendix A).
pub fn (e Eui64) modified_eui64() Eui64 {
mut addr := [8]u8{}
for i in 0 .. 8 {
addr[i] = e.addr[i]
}
addr[0] ^= 0x02
return Eui64{addr}
}
// ipv6 creates new IPv6 address from Modified EUI-64.
// Byte-reversed `prefix` must fit in 64 bit.
// Example:
// ```
// pref := netaddr.Ipv6Net.from_string('2001:0db8:ef01:2345::/64')!
// eui := netaddr.Eui64.from_string('aa-bb-cc-dd-ee-ff-00-11')!
// ip6 := eui.ipv6(pref.network_address)!
// println(ip6) // 2001:0db8:ef01:2345:a8bb:ccdd:eeff:11
// ```
pub fn (e Eui64) ipv6(prefix Ipv6Addr) !Ipv6Addr {
pref := prefix.u8_array_fixed()
eui64 := e.modified_eui64().u8_array_fixed()
if pref[8..] == []u8{len: 8} {
return Ipv6Addr.from_octets([
pref[0],
pref[1],
pref[2],
pref[3],
pref[4],
pref[5],
pref[6],
pref[7],
eui64[0],
eui64[1],
eui64[2],
eui64[3],
eui64[4],
eui64[5],
eui64[6],
eui64[7],
]!)!
}
return error('The prefix ${prefix} is too long. ' +
'At least 64 bits must remain for the interface identifier.')
}
// ipv6_link_local returns link-local IPv6 address created from Modified EUI-64.
pub fn (e Eui64) ipv6_link_local() Ipv6Addr {
return e.ipv6(Ipv6Addr.new(0xfe80, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000) or { Ipv6Addr{} }) or { Ipv6Addr{} }
}
// is_universal returns true if address is universally administreted.
pub fn (e Eui64) is_universal() bool {
// U/L bit is 0
return (e.addr[0] >> 1) & 1 == 0
}
// is_local returns true if address is locally administreted.
pub fn (e Eui64) is_local() bool {
return !e.is_universal()
}
// is_multicast returns true if address is multicast.
pub fn (e Eui64) is_multicast() bool {
return !e.is_unicast()
}
// is_unicast returns true if address is unicast.
pub fn (e Eui64) is_unicast() bool {
// I/G bit is 0
return e.addr[0] & 1 == 0
}
// == returns true if a is equals b.
pub fn (a Eui64) == (b Eui64) bool {
return a.addr == b.addr
}
pub enum Eui64Format {
canonical // e.g. 0a-96-7a-ff-fe-87-4a-e3
unix // e.g. 0a:96:7a:ff:fe:87:4a:e3
hextets // e.g. 0a96.7aff.ffe87.4ae3
bare // e.g. 0a967afffe874ae3
}

547
src/ip.v Normal file
View File

@ -0,0 +1,547 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
import encoding.binary
import math.bits
import net
pub struct Ipv4Addr {
addr [4]u8
}
// Ipv4Addr.new creates new Ipv4Addr instance from four octets.
pub fn Ipv4Addr.new(a u8, b u8, c u8, d u8) Ipv4Addr {
return Ipv4Addr{
addr: [a, b, c, d]!
}
}
// Ipv4Addr.from_octets creates new Ipv4Addr instance from four-element byte array.
pub fn Ipv4Addr.from_octets(addr [4]u8) Ipv4Addr {
return Ipv4Addr{addr}
}
// Ipv4Addr.from_string parses addr string and creates new Ipv4Addr instance.
// Only dotted-decimal form is allowed e.g. 203.0.113.5.
pub fn Ipv4Addr.from_string(addr string) !Ipv4Addr {
octets := addr.split('.')
if octets.len != 4 {
return error('expected 4 octets in ${addr}')
}
mut bytes := [4]u8{}
for i := 0; i < 4; i++ {
bytes[i] = u8(octets[i].parse_uint(10, 8) or {
return error('${octets[i]} is not valid unsigned 8 bit integer in ${addr}')
})
}
return Ipv4Addr{bytes}
}
// Ipv4Addr.from_u32 creates new Ipv4Addr instance from unsigned 32 bit integer.
pub fn Ipv4Addr.from_u32(addr u32) Ipv4Addr {
mut bytes := [4]u8{}
binary.big_endian_put_u32_fixed(mut bytes, addr)
return Ipv4Addr{bytes}
}
// str returns string representation of IP address.
pub fn (a Ipv4Addr) str() string {
// string concatenation is much faster than interpolation
return a.addr[0].str() + '.' + a.addr[1].str() + '.' + a.addr[2].str() + '.' + a.addr[3].str()
}
// u32 returns IP address represented as unsigned 32 bit integer.
pub fn (a Ipv4Addr) u32() u32 {
return binary.big_endian_u32_fixed(a.addr)
}
// u8_array returns IP address represented as byte array.
pub fn (a Ipv4Addr) u8_array() []u8 {
return a.addr[..]
}
// u8_array_fixed returns IP address represented as fixed size byte array.
pub fn (a Ipv4Addr) u8_array_fixed() [4]u8 {
return a.addr
}
// ipv6 returns IPv4-mapped or IPv4-compatible IPv6 address per RFC 4291.
// By default returns the IPv4-mapped IPv6 address e.g. ::ffff:203.0.113.90.
pub fn (a Ipv4Addr) ipv6(params Ipv4ToIpv6Params) Ipv6Addr {
mut bytes := [16]u8{}
if params.kind == .mapped {
bytes[10] = u8(255)
bytes[11] = u8(255)
}
bytes[12] = a.addr[0]
bytes[13] = a.addr[1]
bytes[14] = a.addr[2]
bytes[15] = a.addr[3]
return Ipv6Addr{
addr: bytes
}
}
// bit_len returns number of bits required to represent IP address.
// Example:
// ```
// assert netaddr.Ipv4Addr.new(0, 0, 255, 255).bit_len() == 16
// ```
pub fn (a Ipv4Addr) bit_len() int {
return bits.len_32(a.u32())
}
// family returns the `net.AddrFamily` member corresponding to IP version.
pub fn (a Ipv4Addr) family() net.AddrFamily {
return .ip // net.AddrFamily.ip means IP version 4
}
// reverse_pointer returns reverse DNS record for the IP address in .in-addr.arpa zone.
pub fn (a Ipv4Addr) reverse_pointer() string {
return a.str().split('.').reverse().join('.') + '.in-addr.arpa'
}
// is_link_local returns true if the address is reserved for link-local usage.
pub fn (a Ipv4Addr) is_link_local() bool {
return ipv4_link_local_network.contains(a)
}
// is_loopback returns true if this is a loopback address.
pub fn (a Ipv4Addr) is_loopback() bool {
return ipv4_loopback_network.contains(a)
}
// is_multicast returns true if the address is reserved for multicast use.
pub fn (a Ipv4Addr) is_multicast() bool {
return ipv4_multicast_network.contains(a)
}
// is_unicast returns true if the address is unicast.
pub fn (a Ipv4Addr) is_unicast() bool {
return !a.is_multicast()
}
// is_shared returns true if the address is allocated in shared address space.
// See RFC 6598. Addresses from network 100.64.0.0/10 is both not "private" and
// not "global", so is_private and is_global methods returns false for it.
pub fn (a Ipv4Addr) is_shared() bool {
return ipv4_public_network.contains(a)
}
// is_private returns true if the address is not globally reachable.
pub fn (a Ipv4Addr) is_private() bool {
return ipv4_private_networks.any(it.contains(a) == true)
&& ipv4_private_networks_exceptions.all(it.contains(a) == false)
}
// is_global return true if the address is globally reachable.
pub fn (a Ipv4Addr) is_global() bool {
return !a.is_private() && !ipv4_public_network.contains(a)
}
// is_reserved returns true if the address is IETF reserved.
pub fn (a Ipv4Addr) is_reserved() bool {
return ipv4_reserved_network.contains(a)
}
// is_unspecified returns true if the address is unspecified i.e. equals 0.0.0.0.
pub fn (a Ipv4Addr) is_unspecified() bool {
return a.addr == [4]u8{}
}
// is_netmask returns true if IP address is network mask.
pub fn (a Ipv4Addr) is_netmask() bool {
intval := (a.u32() ^ max_u32) + 1
return intval & (intval - 1) == 0
}
// is_hostmask returns true if IP address is host mask.
pub fn (a Ipv4Addr) is_hostmask() bool {
return (a.u32() + 1) & a.u32() == 0
}
// < returns true if a is lesser than b.
pub fn (a Ipv4Addr) < (b Ipv4Addr) bool {
return a.u32() < b.u32()
}
// == returns true if a equals b.
pub fn (a Ipv4Addr) == (b Ipv4Addr) bool {
return a.addr == b.addr
}
@[params]
pub struct Ipv4ToIpv6Params {
pub:
kind Ipv6WithEmbeddedIpv4 = .mapped
}
// See RFC 4291 Section 2.5.5.
pub enum Ipv6WithEmbeddedIpv4 {
mapped // e.g. ::ffff:203.0.113.90
compat // e.g. ::203.0.113.90, deprecated per RFC 4291 Section 4
}
pub struct Ipv4Net {
pub:
network_address Ipv4Addr
network_mask Ipv4Addr
host_mask Ipv4Addr
broadcast_address Ipv4Addr
host_address ?Ipv4Addr
prefix_len int
mut:
current u32
}
// Ipv4Net.new creates new Ipv4Net from network *addr* with given *prefix* length.
pub fn Ipv4Net.new(addr Ipv4Addr, prefix int) !Ipv4Net {
if prefix < 0 || prefix > 32 {
return error('prefix length must be in range 0-32, not ${prefix}')
}
net_mask := max_u32 ^ (max_u32 >> prefix)
mut net_addr := addr
mut host_addr := ?Ipv4Addr(none)
if (net_addr.u32() & net_mask) != net_addr.u32() {
host_addr = Ipv4Addr{net_addr.u8_array_fixed()}
net_addr = Ipv4Addr.from_u32(net_addr.u32() & net_mask)
}
host_mask := net_mask ^ max_u32
broadcast := net_addr.u32() | host_mask
return Ipv4Net{
network_address: net_addr
network_mask: Ipv4Addr.from_u32(net_mask)
host_mask: Ipv4Addr.from_u32(host_mask)
broadcast_address: Ipv4Addr.from_u32(broadcast)
host_address: host_addr
prefix_len: prefix
current: net_addr.u32()
}
}
// Ipv4Net.from_string parses cidr and creates new Ipv4Net.
// Allowed formats are:
//
// * single IP address without prefix length, 32 is applied;
// * network address with non-negative integer prefix length e.g. 172.16.16.0/24;
// * network address with host mask: 172.16.16.0/0.0.0.255;
// * network address with network mask: 172.16.16.0/255.255.255.0.
//
// If prefix length is greather than 32 and host bits is set in the network address
// the optional `host_address` field will be filled with this host address.
// The `network_address` field always will contain the real network address.
pub fn Ipv4Net.from_string(cidr string) !Ipv4Net {
if cidr.is_blank() {
return error('network address cannot be blank')
}
mut net_addr_str, mut prefix_str := '', ''
cidr_parts := cidr.split_nth('/', 2)
if cidr_parts.len == 1 {
net_addr_str, prefix_str = cidr_parts[0], '32'
} else {
net_addr_str, prefix_str = cidr_parts[0], cidr_parts[1]
}
mut net_addr := Ipv4Addr.from_string(net_addr_str) or {
return error('invalid IPv4 address in ${cidr}')
}
mut prefix_len := 0
mut host_mask := Ipv4Addr{}
mut net_mask := Ipv4Addr.from_u32(max_u32)
mut host_addr := ?Ipv4Addr(none)
if prefix_u64 := prefix_str.parse_uint(10, 32) {
prefix_len = int(prefix_u64)
if prefix_len < 32 {
net_mask = Ipv4Addr.from_u32(max_u32 ^ (max_u32 >> u32(prefix_len)))
}
host_mask = Ipv4Addr.from_u32(net_mask.u32() ^ max_u32)
} else {
mut mask := Ipv4Addr.from_string(prefix_str) or {
return error('invalid prefix length in ${cidr}')
}
if mask.is_netmask() || mask.addr == [4]u8{} || mask.addr == [4]u8{init: 255} {
net_mask = mask
host_mask = Ipv4Addr.from_u32(mask.u32() ^ max_u32)
prefix_len = 32 - host_mask.bit_len()
} else if mask.is_hostmask() {
host_mask = mask
prefix_len = 32 - mask.bit_len()
if prefix_len < 32 {
net_mask = Ipv4Addr.from_u32(max_u32 ^ (max_u32 >> u32(prefix_len)))
}
} else {
return error('${mask} is not valid host or network mask in ${cidr}')
}
}
if (net_addr.u32() & net_mask.u32()) != net_addr.u32() {
host_addr = Ipv4Addr{net_addr.u8_array_fixed()}
net_addr = Ipv4Addr.from_u32(net_addr.u32() & net_mask.u32())
}
broadcast := Ipv4Addr.from_u32(net_addr.u32() | host_mask.u32())
return Ipv4Net{
network_address: net_addr
network_mask: net_mask
host_mask: host_mask
broadcast_address: broadcast
host_address: host_addr
prefix_len: prefix_len
current: net_addr.u32()
}
}
// Ipv4Net.from_u32 creates new Ipv4Net from network *addr* with given *prefix* length.
pub fn Ipv4Net.from_u32(addr u32, prefix int) !Ipv4Net {
if prefix < 0 || prefix > 32 {
return error('prefix length must be in range 0-32, not ${prefix}')
}
mut host_addr := ?Ipv4Addr(none)
mut net_addr := addr
net_mask := max_u32 ^ (max_u32 >> prefix)
if (net_addr & net_mask) != net_addr {
mut net_addr_bytes := [4]u8{}
binary.big_endian_put_u32_fixed(mut net_addr_bytes, net_addr)
host_addr = Ipv4Addr{net_addr_bytes}
net_addr &= net_mask
}
host_mask := net_mask ^ max_u32
broadcast := net_addr | host_mask
return Ipv4Net{
network_address: Ipv4Addr.from_u32(net_addr)
network_mask: Ipv4Addr.from_u32(net_mask)
host_mask: Ipv4Addr.from_u32(host_mask)
broadcast_address: Ipv4Addr.from_u32(broadcast)
host_address: host_addr
prefix_len: prefix
current: net_addr
}
}
// str returns string representation of IPv4 network in CIDR format.
pub fn (n Ipv4Net) str() string {
return n.format(.with_prefix_len)
}
// format returns the IPv4 network as a string formatted according to the fmt rule.
pub fn (n Ipv4Net) format(fmt Ipv4NetFormat) string {
match fmt {
.with_prefix_len {
return n.network_address.str() + '/' + n.prefix_len.str()
}
.with_host_mask {
return n.network_address.str() + '/' + n.host_mask.str()
}
.with_network_mask {
return n.network_address.str() + '/' + n.network_mask.str()
}
}
}
// capacity returns a total number of addresses in the network.
pub fn (n Ipv4Net) capacity() u64 {
return u64(n.broadcast_address.u32() - n.network_address.u32()) + 1
}
// next implements an iterator that iterates over all addresses in network
// including network and broadcast addresses.
// Example:
// ```
// network := netaddr.Ipv4Net.from_string('10.0.10.2/29')!
// for addr in network {
// println(addr)
// }
// ```
pub fn (mut n Ipv4Net) next() ?Ipv4Addr {
if n.current >= n.broadcast_address.u32() + 1 {
return none
}
defer {
n.current++
}
return Ipv4Addr.from_u32(n.current)
}
// first returns the first usable host address in network.
pub fn (n Ipv4Net) first() Ipv4Addr {
if n.prefix_len in [31, 32] {
return n.network_address
}
return Ipv4Addr.from_u32(n.network_address.u32() + 1)
}
// last returns the last usable host address in network.
pub fn (n Ipv4Net) last() Ipv4Addr {
if n.prefix_len in [31, 32] {
return n.broadcast_address
}
return Ipv4Addr.from_u32(n.broadcast_address.u32() - 1)
}
// nth returns the Nth address in network. Supports negative indexes.
pub fn (n Ipv4Net) nth(num i64) !Ipv4Addr {
mut addr := Ipv4Addr{}
if num >= 0 {
addr = Ipv4Addr.from_u32(n.network_address.u32() + u32(num))
} else {
addr = Ipv4Addr.from_u32(n.broadcast_address.u32() + u32(num + 1))
}
if n.contains(addr) {
return addr
}
return error('unable to get ${num}th address')
}
// contains returns true if IP address is in the network.
pub fn (n Ipv4Net) contains(addr Ipv4Addr) bool {
return n.network_address.u32() <= addr.u32() && addr.u32() <= n.broadcast_address.u32()
}
// overlaps returns true if network partly contains in *other*,
// in other words if the networks addresses sets intersect.
pub fn (n Ipv4Net) overlaps(other Ipv4Net) bool {
return other.contains(n.network_address) || (other.contains(n.broadcast_address)
|| (n.contains(other.network_address) || (n.contains(other.broadcast_address))))
}
// subnets returns iterator that iterates over the network subnets partitioned by given *prefix* length.
// Example:
// ```
// network := netaddr.Ipv4Net.from_string('198.51.100.0/24')!
// subnets := network.subnets(26)!
// for subnet in subnets {
// println(subnet)
// }
// ```
pub fn (n Ipv4Net) subnets(prefix int) !Ipv4NetsIterator {
if prefix > 32 || prefix < n.prefix_len {
return error('prefix length must be in range ${n.prefix_len}-32, not ${prefix}')
}
return Ipv4NetsIterator{
prefix_len: prefix
step: (n.host_mask.u32() + 1) >> (prefix - n.prefix_len)
end: n.broadcast_address.u32()
current: n.network_address.u32()
}
}
// supernet returns IPv4 network containing the current network.
pub fn (n Ipv4Net) supernet(prefix int) !Ipv4Net {
if prefix < 0 || prefix > n.prefix_len {
return error('prefix length must be in range 0-${n.prefix_len}, not ${prefix}')
}
if prefix == 0 {
return n
}
net_addr := n.network_address.u32() & (n.network_mask.u32() << (n.prefix_len - prefix))
return Ipv4Net.from_u32(net_addr, prefix)!
}
// is_subnet_of returns true if *other* contains the network.
pub fn (n Ipv4Net) is_subnet_of(other Ipv4Net) bool {
return other.network_address.u32() <= n.network_address.u32()
&& other.broadcast_address.u32() >= n.broadcast_address.u32()
}
// is_supernet_of returns true if the network contains *other*.
pub fn (n Ipv4Net) is_supernet_of(other Ipv4Net) bool {
return n.network_address.u32() <= other.network_address.u32()
&& n.broadcast_address.u32() >= other.broadcast_address.u32()
}
// is_link_local returns true if the network is link-local.
pub fn (n Ipv4Net) is_link_local() bool {
return n.network_address.is_link_local() && n.broadcast_address.is_link_local()
}
// is_loopback returns true if this is a loopback network.
pub fn (n Ipv4Net) is_loopback() bool {
return n.network_address.is_loopback() && n.broadcast_address.is_loopback()
}
// is_multicast returns true if the network is reserved for multicast use.
pub fn (n Ipv4Net) is_multicast() bool {
return n.network_address.is_multicast() && n.broadcast_address.is_multicast()
}
// is_unicast returns true if the network is unicast.
pub fn (n Ipv4Net) is_unicast() bool {
return !n.is_multicast()
}
// is_shared returns true if the network is in shared address space.
pub fn (n Ipv4Net) is_shared() bool {
return n.network_address.is_shared() && n.broadcast_address.is_shared()
}
// is_private returns true if the network is not globally reachable.
pub fn (n Ipv4Net) is_private() bool {
return n.network_address.is_private() && n.broadcast_address.is_private()
}
// is_global return true if the network is globally reachable.
pub fn (n Ipv4Net) is_global() bool {
return !n.is_private()
}
// is_reserved returns true if the network is IETF reserved.
pub fn (n Ipv4Net) is_reserved() bool {
return n.network_address.is_reserved() && n.broadcast_address.is_reserved()
}
// is_unspecified returns true if the network is 0.0.0.0/32.
pub fn (n Ipv4Net) is_unspecified() bool {
return n.network_address.is_unspecified() && n.broadcast_address.is_unspecified()
}
// < returns true if the network is lesser than other network.
pub fn (n Ipv4Net) < (other Ipv4Net) bool {
if n.network_address != other.network_address {
return n.network_address.u32() < other.network_address.u32()
}
if n.network_mask != other.network_mask {
return n.network_mask.u32() < other.network_mask.u32()
}
return false
}
// == returns true if networks equals.
pub fn (n Ipv4Net) == (other Ipv4Net) bool {
return n.network_address == other.network_address && n.network_mask == n.network_mask
}
pub enum Ipv4NetFormat {
with_prefix_len // e.g. 198.51.100.0/24
with_host_mask // e.g. 198.51.100.0/0.0.0.255
with_network_mask // e.g. 198.51.100.0/255.255.255.0
}
pub struct Ipv4NetsIterator {
prefix_len int
step u32
end u32
mut:
current u32
}
// next implements the iterator interface for IP network subnets.
pub fn (mut iter Ipv4NetsIterator) next() ?Ipv4Net {
if iter.current >= iter.end + 1 {
return none
}
defer {
iter.current += iter.step
}
return Ipv4Net.from_u32(iter.current, iter.prefix_len)!
}

884
src/ip6.v Normal file
View File

@ -0,0 +1,884 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
import encoding.binary
import math.big
import net
const max_u128 = big.integer_from_bytes([]u8{len: 16, init: 0xff})
pub struct Ipv6Addr {
addr [16]u8
pub:
zone_id ?string // the IPv6 scope zone identifier per RFC 4007
}
// Ipv6Addr.new creates new Ipv6Addr instance from eight 16-bit segments with optional
// scope zone_id.
// Example:
// ```
// import netaddr
//
// ip := netaddr.Ipv6Addr.new(0x2001, 0x0db8, 0x0008, 0x0004, 0x0000, 0x0000, 0x0000, 0x0002)!
// println(ip) // 2001:db8:8:4::2
// ```
pub fn Ipv6Addr.new(a u16, b u16, c u16, d u16, e u16, f u16, g u16, h u16, params Ipv6AddrParams) !Ipv6Addr {
params.validate()!
mut addr := [16]u8{}
mut one := [2]u8{}
mut nr := 0
for segment in [a, b, c, d, e, f, g, h] {
binary.big_endian_put_u16_fixed(mut one, segment)
addr[nr] = one[0]
addr[nr + 1] = one[1]
nr += 2
}
return Ipv6Addr{
addr: addr
zone_id: params.zone_id
}
}
// Ipv6Addr.from_segments creates new Ipv6Addr instance from eight 16-bit segments
// with optional scope zone_id.
pub fn Ipv6Addr.from_segments(seg [8]u16, params Ipv6AddrParams) !Ipv6Addr {
return Ipv6Addr.new(seg[0], seg[1], seg[2], seg[3], seg[4], seg[5], seg[6], seg[7],
params)!
}
// Ipv6Addr.from_octets creates new Ipv6Addr instance from 16 octets
// with optional scope zone_id.
pub fn Ipv6Addr.from_octets(addr [16]u8, params Ipv6AddrParams) !Ipv6Addr {
params.validate()!
return Ipv6Addr{
addr: addr
zone_id: params.zone_id
}
}
// Ipv6Addr.from_string parses addr and returns new Ipv6Addr instance.
// The allowed formats are:
//
// * full length hexadecimal colon-separated address e.g. aaaa:bbbb:cccc:dddd:eeee:ffff:0000:1111;
// * address with omitted leading zeros in hextets;
// * address with omitted all-zeros hextets e.g. ::1;
// * combined form with omitted all-zeros and leading zeros;
// * mixed with dotted-decimal format e.g. ::ffff:192.168.3.12;
// * address with scope zone identifier e.g. fe80::d08e:6658%eth0;
// * address in square brackets: [a:b:c:d:e:f:0:1].
pub fn Ipv6Addr.from_string(addr string) !Ipv6Addr {
if addr.is_blank() {
return error('IP address cannot be blank')
}
if addr.contains('/') {
return error("unexpected '/' in ${addr}")
}
addr_clean, zone_id := split_scope(addr.trim('[]')) or { return err }
if addr_clean.count('::') > 1 {
return error('too many :: in ${addr}')
}
if addr_clean[0] == u8(`:`) && !addr_clean.starts_with('::') {
return error('leading : is allowed only as :: part in ${addr}')
}
if addr_clean[addr_clean.len - 1] == u8(`:`) && !addr_clean.ends_with('::') {
return error('trailing : is allowed only as :: part in ${addr}')
}
mut hextets := addr_clean.split(':')
if hextets.len < 3 {
return error('at least 3 parts expected in ${addr}')
}
for i, hextet in hextets {
if hextet.contains('.') && i == hextets.len - 1 {
ip4 := Ipv4Addr.from_string(hextet) or {
return error('invalid IPv6-embedded IPv4 address in ${addr}')
}
ip4_u8 := ip4.u8_array_fixed()
hextets.delete(i)
hextets << ip4_u8[0].hex() + ip4_u8[1].hex()
hextets << ip4_u8[2].hex() + ip4_u8[3].hex()
}
}
len_diff := 8 - hextets.len
if len_diff < 8 && len_diff > 0 {
for i := 0; i < len_diff + 1; i++ {
// insert missing hextets with zero values
hextets.insert(hextets.index(''), '0')
}
hextets.delete(hextets.index('')) // delete extra empty item
} else if len_diff < 0 {
// too many hextets (more than 8) in address
return error('unable to parse IPv6 address from string ${addr}')
}
// replace empty strings with zeros
for i := 0; i < hextets.len; i++ {
if hextets[i] == '' {
hextets[i] = '0'
}
}
mut address := [16]u8{}
mut i := 0
for hextet in hextets {
in_hex := '0x' + hextet
if !in_hex.is_hex() {
return error('non-hexadecimal value ${hextet} in ${addr}')
}
mut pair := in_hex.u8_array()
if pair.len == 1 {
// add leading zero to fit into len=2
pair << u8(0)
pair[0], pair[1] = pair[1], pair[0]
}
address[i] = pair[0]
address[i + 1] = pair[1]
i += 2
}
return Ipv6Addr{address, zone_id}
}
// Ipv6Addr.from_bigint creates new Ipv6Addr from big.Integer with optional scope
// zone_id. The integer sign will be discarded. `addr` must fit in 128 bit.
pub fn Ipv6Addr.from_bigint(addr big.Integer, params Ipv6AddrParams) !Ipv6Addr {
params.validate()!
if addr.bit_len() > 128 {
return error('${addr} overflows 128 bit')
}
mut address := [16]u8{}
bytes, _ := addr.bytes()
len_diff := 16 - bytes.len
if len_diff == 0 {
for i in 0 .. 16 {
address[i] = bytes[i]
}
} else {
mut i := 0
for pos in len_diff .. 16 {
address[pos] = bytes[i]
i++
}
}
return Ipv6Addr{
addr: address
zone_id: params.zone_id
}
}
// str returns string representation of IPv6 address in compact format.
pub fn (a Ipv6Addr) str() string {
return a.format(.compact | .dotted)
}
// format returns the IPv6 address as a string formatted according to the fmt rule.
pub fn (a Ipv6Addr) format(fmt Ipv6AddrFormat) string {
mut str := []string{}
match true {
fmt & .compact == .compact {
if fmt & .dotted == .dotted {
if a.is_ipv4_mapped() {
return '::ffff:' +
Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}.str()
}
if a.is_ipv4_compat() {
return '::' + Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}.str()
}
}
for i := 0; i <= 14; i += 2 {
mut hextet := a.addr[i..i + 2].hex().trim_left('0')
if hextet == '' {
hextet = '0'
}
str << hextet
}
// Find largest sequence of zeros and replace it with empty string
mut zeros_seq_begin := -1
mut zeros_seq_len := 0
mut max_zeros_seq_begin := -1
mut max_zeros_seq_len := 0
for i, hx in str {
if hx == '0' {
zeros_seq_len++
if zeros_seq_begin == -1 {
zeros_seq_begin = i
}
if zeros_seq_len > max_zeros_seq_len {
max_zeros_seq_len = zeros_seq_len
max_zeros_seq_begin = zeros_seq_begin
}
} else {
zeros_seq_len = 0
zeros_seq_begin = -1
}
}
if max_zeros_seq_len > 1 {
if str.len == max_zeros_seq_begin + max_zeros_seq_len {
str << ''
}
str.delete_many(max_zeros_seq_begin, max_zeros_seq_len)
if max_zeros_seq_begin == 0 {
str.insert(0, '')
}
str.insert(max_zeros_seq_begin, '')
}
if a.zone_id == none {
return str.join(':')
}
return str.join(':') + '%' + (a.zone_id as string)
}
fmt & .verbose == .verbose {
if fmt & .dotted == .dotted {
if a.is_ipv4_mapped() {
return '0000:0000:0000:0000:0000:ffff:' +
Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}.str()
}
if a.is_ipv4_compat() {
return '0000:0000:0000:0000:0000:0000:' +
Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}.str()
}
}
for i := 0; i <= 14; i += 2 {
str << a.addr[i..i + 2].hex()
}
if a.zone_id == none {
return str.join(':')
}
return str.join(':') + '%' + (a.zone_id as string)
}
else {
return a.str()
}
}
}
// bigint returns IP address represented as big.Integer.
pub fn (a Ipv6Addr) bigint() big.Integer {
if a.addr == [16]u8{} {
return big.zero_int
}
return big.integer_from_bytes(a.addr[..])
}
// u8_array returns IP address represented as byte array.
pub fn (a Ipv6Addr) u8_array() []u8 {
return a.addr[..]
}
// u8_array_fixed returns IP address represented as fixed size byte array.
pub fn (a Ipv6Addr) u8_array_fixed() [16]u8 {
return a.addr
}
// segments returns an array of eight 16-bit IP address segments.
pub fn (a Ipv6Addr) segments() [8]u16 {
mut segments := [8]u16{}
mut nr := 0
for i in 0 .. 8 {
segments[i] = binary.big_endian_u16_fixed([a.addr[nr], a.addr[nr + 1]]!)
nr += 2
}
return segments
}
// with_scope returns IPv6 address with new zone_id.
// Note: with_scope creates new Ipv6Addr, does not change the current.
pub fn (a Ipv6Addr) with_scope(zone_id string) !Ipv6Addr {
if zone_id.is_blank() || zone_id.contains('%') {
return error('zone_id cannot be blank or contain % sign')
}
return Ipv6Addr{a.addr, zone_id}
}
// ipv4 returns IPv4 address converted from IPv4-mapped or IPv4-compatible IPv6 address.
// Note: this function does not treat :: and ::1 addresses as IPv4-compatible ones.
pub fn (a Ipv6Addr) ipv4() !Ipv4Addr {
if a.is_ipv4_mapped() || a.is_ipv4_compat() {
return Ipv4Addr{[a.addr[12], a.addr[13], a.addr[14], a.addr[15]]!}
}
return error('${a} is not IPv4-mapped or IPv4-compatible address')
}
// six_to_four returns embedded IPv4 address if the IPv6 address is 6to4. See RFC 3056.
pub fn (a Ipv6Addr) six_to_four() !Ipv4Addr {
if a.addr[..2] != [u8(0x20), 2] {
return error('${a} is not a 6to4 address')
}
return Ipv4Addr{[a.addr[2], a.addr[3], a.addr[4], a.addr[5]]!}
}
// teredo returns embedded Teredo address.
// See RFC 4380 and https://en.wikipedia.org/wiki/Teredo_tunneling
pub fn (a Ipv6Addr) teredo() !TeredoAddr {
if a.addr[..4] != [u8(0x20), 1, 0, 0] {
return error('${a} is not a Teredo address')
}
return TeredoAddr{
server: Ipv4Addr{[a.addr[4], a.addr[5], a.addr[6], a.addr[7]]!}
flags: binary.big_endian_u16(a.addr[8..10])
port: binary.big_endian_u16([~a.addr[10], ~a.addr[11]])
client: Ipv4Addr{[~a.addr[12], ~a.addr[13], ~a.addr[14], ~a.addr[15]]!}
}
}
// bit_len returns number of bits required to represent IP address.
pub fn (a Ipv6Addr) bit_len() int {
return bit_len_128(a.addr)
}
// family returns the `net.AddrFamily` member corresponding to IP version.
pub fn (a Ipv6Addr) family() net.AddrFamily {
return .ip6
}
// reverse_pointer returns a reverse DNS pointer name for IPv6 address.
pub fn (a Ipv6Addr) reverse_pointer() string {
return a.addr[..].hex().split('').reverse().join('.') + '.ip6.arpa'
}
// is_ipv4_mapped returns true if IPv6 address is IPv4-mapped.
pub fn (a Ipv6Addr) is_ipv4_mapped() bool {
return a.addr[..10].all(it == u8(0)) && a.addr[10] == 255 && a.addr[11] == 255
}
// is_ipv4_compat returns true if IPv6 address is IPv4-compatible.
// Note: loopback and unspecified addresses (::1 and :: respectively) are not
// recognized as IPv4-compatible addresses.
pub fn (a Ipv6Addr) is_ipv4_compat() bool {
return a.addr[..12].all(it == u8(0)) && a.addr[12..16] !in [[u8(0), 0, 0, 0], [u8(0), 0, 0, 1]]
}
// is_site_local returns true if the address is reserved for site local usage.
// See RFC 3879.
pub fn (a Ipv6Addr) is_site_local() bool {
return ipv6_site_local_network.contains(a)
}
// is_unique_local returns true if the address is unique local. See RFC 4193, RFC 8190.
pub fn (a Ipv6Addr) is_unique_local() bool {
return ipv6_unique_local_network.contains(a)
}
// is_link_local returns true if the address is allocated in link-local network.
pub fn (a Ipv6Addr) is_link_local() bool {
ip := a.ipv4() or { return ipv6_link_local_network.contains(a) }
return ip.is_link_local()
}
// is_loopback returns true if the address is loopback i.e equals ::1.
pub fn (a Ipv6Addr) is_loopback() bool {
ip := a.ipv4() or { return a.addr == [u8(0), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]! }
return ip.is_loopback()
}
// is_multicast returns true if the address is reserved for multicast use.
pub fn (a Ipv6Addr) is_multicast() bool {
ip := a.ipv4() or { return ipv6_multicast_network.contains(a) }
return ip.is_multicast()
}
// is_unicast returns true if the address is unicast.
pub fn (a Ipv6Addr) is_unicast() bool {
return !a.is_multicast()
}
// is_private returns true if the address is not globally reachable.
pub fn (a Ipv6Addr) is_private() bool {
ip := a.ipv4() or {
return ipv6_private_networks.any(it.contains(a) == true)
&& ipv6_private_networks_exceptions.all(it.contains(a) == false)
}
return ip.is_private()
}
// is_global return true if the address is globally reachable.
pub fn (a Ipv6Addr) is_global() bool {
return !a.is_private()
}
// is_reserved returns true if the address is allocated in reserved networks.
pub fn (a Ipv6Addr) is_reserved() bool {
ip := a.ipv4() or { return ipv6_reserved_networks.any(it.contains(a) == true) }
return ip.is_reserved()
}
// is_unspecified returns true if IP address is unspecified i.e equals ::.
pub fn (a Ipv6Addr) is_unspecified() bool {
ip := a.ipv4() or { return a.addr == [16]u8{} }
return ip.is_unspecified()
}
// is_netmask returns true if IP address is network mask.
pub fn (a Ipv6Addr) is_netmask() bool {
val := a.bigint().bitwise_xor(max_u128) + big.one_int
return val.bitwise_and(val - big.one_int) == big.zero_int
}
// is_hostmask returns true if IP address is host mask.
pub fn (a Ipv6Addr) is_hostmask() bool {
addr_num := a.bigint()
return (addr_num + big.one_int).bitwise_and(addr_num) == big.zero_int
}
// < returns true if a is lesser than b.
pub fn (a Ipv6Addr) < (b Ipv6Addr) bool {
return compare_128(a.addr, b.addr) == -1
}
// == returns true if a equals b.
pub fn (a Ipv6Addr) == (b Ipv6Addr) bool {
return a.addr == b.addr
}
fn split_scope(addr string) !(string, ?string) {
address, zone_id := addr.split_once('%') or { '', 'empty' }
if zone_id == '' || zone_id.contains('%') {
return error('invalid zone_id in ${addr}')
}
if address == '' {
return addr, ?string(none)
}
return address, zone_id
}
@[params]
pub struct Ipv6AddrParams {
pub:
zone_id ?string
}
fn (p Ipv6AddrParams) validate() ! {
if p.zone_id != none {
zone_id := p.zone_id as string
if zone_id.is_blank() || zone_id.contains('%') {
return error('zone_id cannot be blank or contain % sign')
}
}
}
@[flag]
pub enum Ipv6AddrFormat {
compact // e.g. fe80::896:7aff:e87:4ae3
verbose // e.g. fe80:0000:0000:0000:0896:7aff:0e87:4ae3
dotted // use dotted-decimal notation for IPv4-mapped and IPv4-compat addresses e.g. ::ffff:192.168.3.11
}
// TeredoAddr represents the parsed Teredo address. See RFC 4380 Section 4.
pub struct TeredoAddr {
pub:
server Ipv4Addr
flags u16
port u16
client Ipv4Addr
}
// ipv6 returns Ipv6Addr created from Teredo address.
@[direct_array_access]
pub fn (t TeredoAddr) ipv6() Ipv6Addr {
mut addr := [16]u8{}
addr[0] = u8(0x20)
addr[1] = u8(0x01)
mut flags := [2]u8{}
binary.big_endian_put_u16_fixed(mut flags, t.flags)
addr[8] = flags[0]
addr[9] = flags[1]
mut port := [2]u8{}
binary.big_endian_put_u16_fixed(mut port, t.port)
addr[10] = ~port[0]
addr[11] = ~port[1]
for i := 4; i < 8; i++ {
addr[i] = t.server.addr[i - 4]
addr[i + 8] = ~t.client.addr[i - 4]
}
return Ipv6Addr{
addr: addr
}
}
pub struct Ipv6Net {
pub:
network_address Ipv6Addr
network_mask Ipv6Addr
host_mask Ipv6Addr
broadcast_address Ipv6Addr
host_address ?Ipv6Addr
prefix_len int
mut:
current big.Integer
}
// Ipv6Net.new creates new IPv6 network from given Ipv6Addr and prefix.
pub fn Ipv6Net.new(addr Ipv6Addr, prefix int) !Ipv6Net {
if prefix < 0 || prefix > 128 {
return error('prefix length must be in range 0-128, not ${prefix}')
}
mut net_addr := addr
mut host_addr := ?Ipv6Addr(none)
net_mask := Ipv6Addr{
addr: bitwise_xor_128(max_128, right_shift_128(max_128, prefix))
}
if bitwise_and_128(net_addr.addr, net_mask.addr) != net_addr.u8_array_fixed() {
host_addr = Ipv6Addr{
addr: net_addr.addr
}
net_addr = Ipv6Addr{
addr: bitwise_and_128(net_addr.addr, net_mask.addr)
}
}
host_mask := Ipv6Addr{
addr: bitwise_xor_128(net_mask.addr, max_128)
}
broadcast := Ipv6Addr{
addr: bitwise_or_128(net_addr.addr, host_mask.addr)
}
return Ipv6Net{
network_address: net_addr
network_mask: net_mask
host_mask: host_mask
broadcast_address: broadcast
host_address: host_addr
prefix_len: prefix
current: net_addr.bigint()
}
}
// Ipv6Net.from_string parses cidr and creates new Ipv6Net.
// All formats supported by Ipv6Addr.from_string is allowed here.
// See also Ipv4Net.from_string for additional info about parsing strategy and
// supported network/prefix variants.
pub fn Ipv6Net.from_string(cidr string) !Ipv6Net {
net_addr_str, prefix_str := cidr.split_once('/') or { cidr, '128' }
mut net_addr := Ipv6Addr.from_string(net_addr_str)!
mut prefix_len := 0
mut host_mask := Ipv6Addr{}
mut net_mask := Ipv6Addr{
addr: [16]u8{init: 0xff}
}
mut host_addr := ?Ipv6Addr(none)
if prefix_len_u64 := prefix_str.parse_uint(10, 64) {
prefix_len = int(prefix_len_u64)
if prefix_len < 128 {
net_mask = Ipv6Addr{
addr: bitwise_xor_128(max_128, right_shift_128(max_128, prefix_len))
}
}
host_mask = Ipv6Addr{
addr: bitwise_xor_128(net_mask.addr, max_128)
}
} else {
mut mask := Ipv6Addr.from_string(prefix_str)!
match true {
mask.is_netmask() || mask.addr == [16]u8{} || mask.addr == [16]u8{init: 0xff} {
net_mask = mask
host_mask = Ipv6Addr{
addr: bitwise_xor_128(mask.addr, max_128)
}
prefix_len = 128 - host_mask.bit_len()
}
mask.is_hostmask() {
host_mask = mask
prefix_len = 128 - host_mask.bit_len()
if prefix_len < 128 {
net_mask = Ipv6Addr{
addr: bitwise_xor_128(max_128, right_shift_128(max_128, prefix_len))
}
}
}
else {
return error('${mask} is not valid network or host mask in ${cidr}')
}
}
}
if bitwise_and_128(net_addr.addr, net_mask.addr) != net_addr.u8_array_fixed() {
host_addr = Ipv6Addr{
addr: net_addr.u8_array_fixed()
}
net_addr = Ipv6Addr{
addr: bitwise_and_128(net_addr.u8_array_fixed(), net_mask.addr)
}
}
broadcast := Ipv6Addr{
addr: bitwise_or_128(net_addr.addr, host_mask.addr)
}
return Ipv6Net{
network_address: net_addr
network_mask: net_mask
host_mask: host_mask
broadcast_address: broadcast
host_address: host_addr
prefix_len: prefix_len
current: net_addr.bigint()
}
}
// Ipv6Net.from_bigint creates new IPv6 network from given addr and prefix.
// `addr` must fit in 128 bits.
pub fn Ipv6Net.from_bigint(addr big.Integer, prefix int) !Ipv6Net {
if prefix < 0 || prefix > 128 {
return error('prefix length must be in range 0-128, not ${prefix}')
}
if addr.bit_len() > 128 {
return error('${addr} overflows 128 bit')
}
mut host_addr := ?Ipv6Addr(none)
mut net_addr := addr
net_mask := max_u128.bitwise_xor(max_u128.right_shift(u32(prefix)))
if net_addr.bitwise_and(net_mask) != net_addr {
host_addr = Ipv6Addr.from_bigint(net_addr)!
net_addr = net_addr.bitwise_and(net_mask)
}
host_mask := net_mask.bitwise_xor(max_u128)
broadcast := net_addr.bitwise_or(host_mask)
return Ipv6Net{
network_address: Ipv6Addr.from_bigint(net_addr)!
network_mask: Ipv6Addr.from_bigint(net_mask)!
host_mask: Ipv6Addr.from_bigint(host_mask)!
broadcast_address: Ipv6Addr.from_bigint(broadcast)!
host_address: host_addr
prefix_len: prefix
current: net_addr
}
}
// str returns string representation of IPv6 network in CIDR format.
pub fn (n Ipv6Net) str() string {
return n.format(.compact | .dotted | .with_prefix_len)
}
// format returns the IPv6 network as a string formatted according to the fmt rule.
pub fn (n Ipv6Net) format(fmt Ipv6NetFormat) string {
addr_fmt := Ipv6AddrFormat(fmt)
match true {
fmt & .with_prefix_len == .with_prefix_len {
return n.network_address.format(addr_fmt) + '/' + n.prefix_len.str()
}
fmt & .with_network_mask == .with_network_mask {
return n.network_address.format(addr_fmt) + '/' + n.network_mask.format(addr_fmt)
}
fmt & .with_host_mask == .with_host_mask {
return n.network_address.format(addr_fmt) + '/' + n.host_mask.format(addr_fmt)
}
else {
return n.format(fmt | .with_prefix_len)
}
}
}
// capacity returns a total number of addresses in the network.
pub fn (n Ipv6Net) capacity() big.Integer {
return (n.broadcast_address.bigint() - n.network_address.bigint()) + big.one_int
}
// next implements an iterator that iterates over all addresses in network
// including network and broadcast addresses.
// Example:
// ```
// network := netaddr.Ipv6Net.from_string('fe80::/124')!
// for addr in network {
// println(addr)
// }
// ```
pub fn (mut n Ipv6Net) next() ?Ipv6Addr {
if n.current >= n.broadcast_address.bigint() + big.one_int {
return none
}
defer {
n.current = n.current + big.one_int
}
return Ipv6Addr.from_bigint(n.current)!
}
// first returns the first usable host address in network.
pub fn (n Ipv6Net) first() Ipv6Addr {
if n.prefix_len in [127, 128] {
return n.network_address
}
return Ipv6Addr.from_bigint(n.network_address.bigint() + big.one_int) or { panic(err) }
}
// last returns the last usable host address in network.
pub fn (n Ipv6Net) last() Ipv6Addr {
if n.prefix_len in [127, 128] {
return n.broadcast_address
}
return Ipv6Addr.from_bigint(n.broadcast_address.bigint() - big.one_int) or { panic(err) }
}
// nth returns the Nth address in network. Supports negative indexes.
pub fn (n Ipv6Net) nth(num big.Integer) !Ipv6Addr {
mut addr := Ipv6Addr{}
if num >= big.zero_int {
addr = Ipv6Addr.from_bigint(n.network_address.bigint() + num)!
} else {
addr = Ipv6Addr.from_bigint(n.broadcast_address.bigint() + num + big.one_int)!
}
if n.contains(addr) {
return addr
}
return error('unable to get ${num}th address')
}
// contains returns true if IP address is in the network.
pub fn (n Ipv6Net) contains(addr Ipv6Addr) bool {
return n.network_address <= addr && addr <= n.broadcast_address
}
// overlaps returns true if network partly contains in *other*,
// in other words if the networks addresses sets intersect.
pub fn (n Ipv6Net) overlaps(other Ipv6Net) bool {
return other.contains(n.network_address) || (other.contains(n.broadcast_address)
|| (n.contains(other.network_address) || (n.contains(other.broadcast_address))))
}
// subnets returns iterator that iterates over the network subnets partitioned by given *prefix* length.
// Example:
// ```
// network := netaddr.Ipv6Net.from_string('2001:db8:beaf::/56')!
// subnets := network.subnets(64)!
// for subnet in subnets {
// println(subnet)
// }
// ```
pub fn (n Ipv6Net) subnets(prefix int) !Ipv6NetsIterator {
if prefix > 128 || prefix < n.prefix_len {
return error('prefix length must be in range ${n.prefix_len}-128, not ${prefix}')
}
return Ipv6NetsIterator{
prefix_len: prefix
step: (n.host_mask.bigint() + big.one_int).right_shift(u32(prefix - n.prefix_len))
end: n.broadcast_address.bigint()
current: n.network_address.bigint()
}
}
// supernet returns IPv6 network containing the current network.
pub fn (n Ipv6Net) supernet(prefix int) !Ipv6Net {
if prefix < 0 || prefix > n.prefix_len {
return error('prefix length must be in range 0-${n.prefix_len}, not ${prefix}')
}
if prefix == 0 {
return n
}
net_addr := Ipv6Addr{
addr: bitwise_and_128(n.network_address.addr, left_shift_128(n.network_mask.addr,
n.prefix_len - prefix))
}
return Ipv6Net.new(net_addr, prefix)!
}
// is_subnet_of returns true if *other* contains the network.
pub fn (n Ipv6Net) is_subnet_of(other Ipv6Net) bool {
return other.network_address <= n.network_address
&& other.broadcast_address >= n.broadcast_address
}
// is_supernet_of returns true if the network contains *other*.
pub fn (n Ipv6Net) is_supernet_of(other Ipv6Net) bool {
return n.network_address <= other.network_address
&& n.broadcast_address >= other.broadcast_address
}
// is_site_local returns true if the network is site-local.
pub fn (n Ipv6Net) is_site_local() bool {
return n.network_address.is_site_local() && n.broadcast_address.is_site_local()
}
// is_unique_local returns true if the network is unique-local.
pub fn (n Ipv6Net) is_unique_local() bool {
return n.network_address.is_unique_local() && n.broadcast_address.is_unique_local()
}
// is_link_local returns true if the network is link-local.
pub fn (n Ipv6Net) is_link_local() bool {
return n.network_address.is_link_local() && n.broadcast_address.is_link_local()
}
// is_loopback returns true if this is a loopback network.
pub fn (n Ipv6Net) is_loopback() bool {
return n.network_address.is_loopback() && n.broadcast_address.is_loopback()
}
// is_multicast returns true if the network is reserved for multicast use.
pub fn (n Ipv6Net) is_multicast() bool {
return n.network_address.is_multicast() && n.broadcast_address.is_multicast()
}
// is_unicast returns true if the network is unicast.
pub fn (n Ipv6Net) is_unicast() bool {
return !n.is_multicast()
}
// is_private returns true if the network is not globally reachable.
pub fn (n Ipv6Net) is_private() bool {
return n.network_address.is_private() && n.broadcast_address.is_private()
}
// is_global return true if the network is globally reachable.
pub fn (n Ipv6Net) is_global() bool {
return !n.is_private()
}
// is_reserved returns true if the network is reserved.
pub fn (n Ipv6Net) is_reserved() bool {
return n.network_address.is_reserved() && n.broadcast_address.is_reserved()
}
// is_unspecified returns true if the network is ::/0.
pub fn (n Ipv6Net) is_unspecified() bool {
return n.network_address.is_unspecified() && n.broadcast_address.is_unspecified()
}
// < returns true if the network is lesser than other network.
pub fn (n Ipv6Net) < (other Ipv6Net) bool {
if n.network_address != other.network_address {
return n.network_address < other.network_address
}
if n.network_mask != other.network_mask {
return n.network_mask < other.network_mask
}
return false
}
// == returns true if networks equals.
pub fn (n Ipv6Net) == (other Ipv6Net) bool {
return n.network_address == other.network_address && n.network_mask == n.network_mask
}
@[flag]
pub enum Ipv6NetFormat {
compact
verbose
dotted
with_prefix_len
with_host_mask
with_network_mask
}
pub struct Ipv6NetsIterator {
prefix_len int
step big.Integer
end big.Integer
mut:
current big.Integer
}
// next implements the iterator interface for IP network subnets.
pub fn (mut iter Ipv6NetsIterator) next() ?Ipv6Net {
if iter.current >= iter.end + big.one_int {
return none
}
defer {
iter.current += iter.step
}
return Ipv6Net.from_bigint(iter.current, iter.prefix_len)!
}

294
src/ip6_const.v Normal file
View File

@ -0,0 +1,294 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
// This file contains pre-calculated values for IPv6 reserved networks.
// See https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
module netaddr
struct Ipv6Const {
begin [16]u8
end [16]u8
}
fn (n Ipv6Const) contains(addr Ipv6Addr) bool {
// There is: n.begin <= addr && addr <= n.end
return compare_128(n.begin, addr.addr) in [-1, 0] && compare_128(addr.addr, n.end) in [-1, 0]
}
// fec0::/10
const ipv6_site_local_network = Ipv6Const{
begin: [u8(0xfe), 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00]!
end: [u8(0xfe), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff]!
}
// fc00::/7
const ipv6_unique_local_network = Ipv6Const{
begin: [u8(0xfc), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00]!
end: [u8(0xfd), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff]!
}
// fe80::/10
const ipv6_link_local_network = Ipv6Const{
begin: [u8(0xfe), 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00]!
end: [u8(0xfe), 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff]!
}
// ff00::/8
const ipv6_multicast_network = Ipv6Const{
begin: [u8(0xff), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00]!
end: [u8(0xff), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff]!
}
const ipv6_reserved_networks = [
// ::/8
Ipv6Const{
begin: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x00), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 100::/8
Ipv6Const{
begin: [u8(0x01), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x01), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 200::/7
Ipv6Const{
begin: [u8(0x02), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x03), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 400::/6
Ipv6Const{
begin: [u8(0x04), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x07), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 800::/5
Ipv6Const{
begin: [u8(0x08), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x0f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 1000::/4
Ipv6Const{
begin: [u8(0x10), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x1f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 4000::/3
Ipv6Const{
begin: [u8(0x40), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x5f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 6000::/3
Ipv6Const{
begin: [u8(0x60), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x7f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 8000::/3
Ipv6Const{
begin: [u8(0x80), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x9f), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// a000::/3
Ipv6Const{
begin: [u8(0xa0), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xbf), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// c000::/3
Ipv6Const{
begin: [u8(0xc0), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xdf), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// e000::/4
Ipv6Const{
begin: [u8(0xe0), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xef), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// f000::/5
Ipv6Const{
begin: [u8(0xf0), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xf7), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// f800::/6
Ipv6Const{
begin: [u8(0xf8), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xfb), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// fe00::/9
Ipv6Const{
begin: [u8(0xfe), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xfe), 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
]!
const ipv6_private_networks = [
// ::1/128
Ipv6Const{
begin: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01]!
end: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01]!
},
// ::/128
Ipv6Const{
begin: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
},
// ::ffff:0:0/96
Ipv6Const{
begin: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x00), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 64:ff9b:1::/48
Ipv6Const{
begin: [u8(0x00), 0x64, 0xff, 0x9b, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x00), 0x64, 0xff, 0x9b, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 100::/64
Ipv6Const{
begin: [u8(0x01), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x01), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001::/23
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001:db8::/32
Ipv6Const{
begin: [u8(0x20), 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x0d, 0xb8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2002::/16
Ipv6Const{
begin: [u8(0x20), 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 3fff::/20
Ipv6Const{
begin: [u8(0x3f), 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x3f), 0xff, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// fc00::/7 (unique-local)
Ipv6Const{
begin: [u8(0xfc), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xfd), 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// fe80::/10 (link-local)
Ipv6Const{
begin: [u8(0xfe), 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0xfe), 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
]!
const ipv6_private_networks_exceptions = [
// 2001:1::1/128
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01]!
end: [u8(0x20), 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01]!
},
// 2001:1::2/128
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02]!
end: [u8(0x20), 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02]!
},
// 2001:3::/32
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x00, 0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001:4:112::/48
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x04, 0x01, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x00, 0x04, 0x01, 0x12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001:20::/28
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x00, 0x2f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
// 2001:30::/28
Ipv6Const{
begin: [u8(0x20), 0x01, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00]!
end: [u8(0x20), 0x01, 0x00, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff]!
},
]!

77
src/ip_const.v Normal file
View File

@ -0,0 +1,77 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
// This file contains pre-calculated values for IPv4 reserved networks.
// See https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
module netaddr
struct Ipv4Const {
begin u32
end u32
}
fn (n Ipv4Const) contains(addr Ipv4Addr) bool {
return n.begin <= addr.u32() && addr.u32() <= n.end
}
// 169.254.0.0/16
const ipv4_link_local_network = Ipv4Const{u32(2851995648), u32(2852061183)}
// 127.0.0.0/8
const ipv4_loopback_network = Ipv4Const{u32(2130706432), u32(2147483647)}
// 224.0.0.0/4
const ipv4_multicast_network = Ipv4Const{u32(3758096384), u32(4026531839)}
// 100.64.0.0/10
const ipv4_public_network = Ipv4Const{u32(1681915904), u32(1686110207)}
// 240.0.0.0/4
const ipv4_reserved_network = Ipv4Const{u32(4026531840), u32(4294967295)}
const ipv4_private_networks = [
// 0.0.0.0/8
Ipv4Const{u32(0), u32(16777215)},
// 10.0.0.0/8
Ipv4Const{u32(167772160), u32(184549375)},
// 169.254.0.0/16
Ipv4Const{u32(2851995648), u32(2852061183)}
// 127.0.0.0/8
Ipv4Const{u32(2130706432), u32(2147483647)}
// 172.16.0.0/12
Ipv4Const{u32(2886729728), u32(2887778303)},
// 192.0.0.0/24
Ipv4Const{u32(3221225472), u32(3221225727)},
// 192.0.0.170/31
Ipv4Const{u32(3221225642), u32(3221225643)},
// 192.0.2.0/24
Ipv4Const{u32(3221225984), u32(3221226239)},
// 192.168.0.0/16
Ipv4Const{u32(3232235520), u32(3232301055)},
// 198.18.0.0/15
Ipv4Const{u32(3323068416), u32(3323199487)},
// 198.51.100.0/24
Ipv4Const{u32(3325256704), u32(3325256959)},
// 203.0.113.0/24
Ipv4Const{u32(3405803776), u32(3405804031)},
// 240.0.0.0/4
Ipv4Const{u32(4026531840), u32(4294967295)}
// 255.255.255.255/32
Ipv4Const{u32(4294967295), u32(4294967295)},
]!
const ipv4_private_networks_exceptions = [
// 192.0.0.9/32
Ipv4Const{u32(3221225481), u32(3221225481)},
// 192.0.0.10/32
Ipv4Const{u32(3221225482), u32(3221225482)},
]!

98
src/sumtypes.v Normal file
View File

@ -0,0 +1,98 @@
// This file is part of netaddr.
//
// netaddr is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// netaddr is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with netaddr. If not, see <https://www.gnu.org/licenses/>.
module netaddr
pub type IpAddr = Ipv4Addr | Ipv4Net | Ipv6Addr | Ipv6Net
// IpAddr.from_string parses the addr string and returns IP address or IP network.
// This is universal function that processes both internet protocol versions.
//
// This function accepts all of the IP address and network formats allowed in
// Ipv4Addr.from_string, Ipv4Net.from_string, Ipv6Addr.from_string
// and Ipv6Net.from_string.
//
// Example:
// ```
// ip := netaddr.IpAddr.from_string('2001:db8:beaf::/56')!
// match ip {
// netaddr.Ipv4Addr {
// println('${ip} is IPv4 address')
// }
// netaddr.Ipv4Net {
// println('${ip} is IPv4 network')
// }
// netaddr.Ipv6Addr {
// println('${ip} is IPv6 address')
// }
// netaddr.Ipv6Net {
// println('${ip} is IPv6 network')
// }
// }
// ```
pub fn IpAddr.from_string(addr string) !IpAddr {
if addr.contains('/') {
if result := Ipv4Net.from_string(addr) {
return result
}
if result := Ipv6Net.from_string(addr) {
return result
}
}
if result := Ipv4Addr.from_string(addr) {
return result
}
if result := Ipv6Addr.from_string(addr) {
return result
}
return error('${addr} is not a valid IPv4 or IPv6 address or network')
}
// str returns the IP string representation.
pub fn (ip IpAddr) str() string {
return match ip {
Ipv4Addr { ip.str() }
Ipv6Addr { ip.str() }
Ipv4Net { ip.str() }
Ipv6Net { ip.str() }
}
}
pub type Eui = Eui48 | Eui64
// Eui.from_string parses addr string and returns EUI-48 or EUI-64.
// Example:
// ```v okfmt
// cmd := os.execute('ip -br link show wlan0')
// interface_id := netaddr.Eui.from_string(cmd.output.split_by_space()[2])!
// println(interface_id)
// ```
pub fn Eui.from_string(addr string) !Eui {
if result := Eui48.from_string(addr) {
return result
}
if result := Eui64.from_string(addr) {
return result
}
return error('${addr} is not valid EUI-48 or EUI-64')
}
// str returns the EUI string representation.
pub fn (eui Eui) str() string {
return match eui {
Eui48 { eui.str() }
Eui64 { eui.str() }
}
}

40
tests/eui48_test.v Normal file
View File

@ -0,0 +1,40 @@
import netaddr
fn test_eui48_from_string() {
expected := netaddr.Eui48.from_octets([u8(0x0a), 0x96, 0x7a, 0x87, 0x4a, 0xe3]!)
assert netaddr.Eui48.from_string('0a-96-7a-87-4a-e3')! == expected
assert netaddr.Eui48.from_string('0a:96:7a:87:4a:e3')! == expected
assert netaddr.Eui48.from_string('0a96.7a87.4ae3')! == expected
assert netaddr.Eui48.from_string('0a967a874ae3')! == expected
assert netaddr.Eui48.from_string(u64(4123532145345345).hex()) or { netaddr.Eui48{} } == netaddr.Eui48{}
}
fn test_eui48_format() {
mac := netaddr.Eui48.from_octets([u8(0x0a), 0x96, 0x7a, 0x87, 0x4a, 0xe3]!)
assert mac.str() == '0a-96-7a-87-4a-e3'
assert mac.format(.canonical) == '0a-96-7a-87-4a-e3'
assert mac.format(.unix) == '0a:96:7a:87:4a:e3'
assert mac.format(.hextets) == '0a96.7a87.4ae3'
assert mac.format(.bare) == '0a967a874ae3'
assert netaddr.Eui48{}.format(.hextets) == '0000.0000.0000'
}
fn test_eui48_tests() {
mac := netaddr.Eui48.from_octets([u8(0x10), 0xff, 0xe0, 0x4b, 0xe6, 0xb8]!)
assert mac.is_universal()
assert mac.is_unicast()
}
fn test_eui48_ipv6_link_local() {
mac := netaddr.Eui48.from_octets([u8(0x10), 0xff, 0xe0, 0x4b, 0xe6, 0xb8]!)
assert mac.ipv6_link_local().str() == 'fe80::12ff:e0ff:fe4b:e6b8'
}
fn test_eui48_random() {
mac_a := netaddr.Eui48.random()
assert mac_a.is_local()
assert mac_a.is_unicast()
mac_b := netaddr.Eui48.random(oui: [u8(0x02), 0x00, 0x00]!)
assert mac_b.is_local()
assert mac_b.is_unicast()
}

22
tests/eui64_test.v Normal file
View File

@ -0,0 +1,22 @@
import netaddr
fn test_eui48_from_string() {
expected := netaddr.Eui64.new(0x0a, 0x96, 0x7a, 0xff, 0xfe, 0x87, 0x4a, 0xe3)
assert netaddr.Eui64.from_string('0a-96-7a-ff-fe-87-4a-e3')! == expected
assert netaddr.Eui64.from_string('0a:96:7a:ff:fe:87:4a:e3')! == expected
assert netaddr.Eui64.from_string('0a96.7aff.fe87.4ae3')! == expected
assert netaddr.Eui64.from_string('0a967afffe874ae3')! == expected
}
fn test_eui48_format() {
eui := netaddr.Eui64.new(0x0a, 0x96, 0x7a, 0xff, 0xfe, 0x87, 0x4a, 0xe3)
assert eui.str() == '0a-96-7a-ff-fe-87-4a-e3'
assert eui.format(.canonical) == '0a-96-7a-ff-fe-87-4a-e3'
assert eui.format(.unix) == '0a:96:7a:ff:fe:87:4a:e3'
assert eui.format(.hextets) == '0a96.7aff.fe87.4ae3'
assert eui.format(.bare) == '0a967afffe874ae3'
assert netaddr.Eui64{}.format(.hextets) == '0000.0000.0000.0000'
}
fn test_eui64_modified() {
}

224
tests/ip6_test.v Normal file
View File

@ -0,0 +1,224 @@
import math.big
import netaddr
fn test_ipv6_addr_new() {
a := netaddr.Ipv6Addr.new(0x2001, 0x0db8, 0x0008, 0x0004, 0x0000, 0x0000, 0x0000,
0x0002)!
b := netaddr.Ipv6Addr.new(0xfe80, 0x0000, 0x0000, 0x0000, 0xd08e, 0x6658, 0x38bd,
0x6391,
zone_id: 'wlan0'
)!
assert a.str() == '2001:db8:8:4::2'
assert b.str() == 'fe80::d08e:6658:38bd:6391%wlan0'
}
fn test_ipv6_add_segments() {
ip := netaddr.Ipv6Addr.new(0x2001, 0x0db8, 0x0008, 0x0004, 0x0000, 0x0000, 0x0000,
0x0002)!
assert ip.segments() == [u16(0x2001), 0x0db8, 0x0008, 0x0004, 0x0000, 0x0000, 0x0000, 0x0002]!
}
fn test_ipv6_addr_from_to_bigint() {
bigint := big.integer_from_string('338288524927261089661396923005694177083')!
addr := netaddr.Ipv6Addr.from_bigint(bigint)!
assert addr.format(.verbose) == 'fe80:0000:0000:0000:6664:03b4:bd68:ef3b'
assert addr.bigint() == bigint
addr2 := netaddr.Ipv6Addr.from_string('fe80:0000:0000:0000:6664:03b4:bd68:ef3b')!
assert addr2.bigint() == bigint
}
fn test_ipv6_addr_from_string_zeros() {
assert netaddr.Ipv6Addr.from_string('::')!.bigint() == big.zero_int
}
fn test_ipv6_addr_from_string() {
addrs := {
'fe80:0000:0000:0000:0896:7aff:0e87:4ae3': 'fe80::896:7aff:e87:4ae3'
'fe80:0:0:0:896:7aff:e87:4ae3': 'fe80::896:7aff:e87:4ae3'
'fe80::896:7aff:e87:4ae3': 'fe80::896:7aff:e87:4ae3'
'fe80::896:7aff:e87:4ae3%1': 'fe80::896:7aff:e87:4ae3%1'
'[fe80::896:7aff:e87:4ae3%2]': 'fe80::896:7aff:e87:4ae3%2'
'0:0:0:0:0:0:0:0': '::'
'0000:0000:0000:0000:0000:0000:0000:0000': '::'
'::': '::'
'::1': '::1'
'0:0:ff::': '0:0:ff::'
'0:0:ff::1': '0:0:ff::1'
'::ffff:1:2:3:4': '::ffff:1:2:3:4'
'::192.168.1.1': '::192.168.1.1'
}
for inp, out in addrs {
assert netaddr.Ipv6Addr.from_string(inp)!.str() == out
}
}
fn test_ipv6_addr_format() {
addr1 := netaddr.Ipv6Addr.from_string('fe80::896:7aff:e87:4ae3')!
assert addr1.format(.dotted) == 'fe80::896:7aff:e87:4ae3'
assert addr1.format(.compact) == 'fe80::896:7aff:e87:4ae3'
assert addr1.format(.compact | .dotted) == 'fe80::896:7aff:e87:4ae3'
assert addr1.format(.verbose) == 'fe80:0000:0000:0000:0896:7aff:0e87:4ae3'
assert addr1.format(.verbose | .dotted) == 'fe80:0000:0000:0000:0896:7aff:0e87:4ae3'
assert addr1.format(.compact | .verbose | .dotted) == 'fe80::896:7aff:e87:4ae3'
addr2 := netaddr.Ipv6Addr.from_string('::ffff:192.168.3.8')!
assert addr2.format(.dotted) == '::ffff:192.168.3.8'
assert addr2.format(.compact) == '::ffff:c0a8:308'
assert addr2.format(.compact | .dotted) == '::ffff:192.168.3.8'
assert addr2.format(.verbose) == '0000:0000:0000:0000:0000:ffff:c0a8:0308'
assert addr2.format(.verbose | .dotted) == '0000:0000:0000:0000:0000:ffff:192.168.3.8'
assert addr2.format(.compact | .verbose | .dotted) == '::ffff:192.168.3.8'
}
fn test_ipv6_addr_dns_ptr() {
expect := '1.9.3.6.d.b.8.3.8.5.6.6.e.8.0.d.0.0.0.0.0.0.0.0.0.0.0.0.0.8.e.f.ip6.arpa'
assert netaddr.Ipv6Addr.from_string('fe80::d08e:6658:38bd:6391')!.reverse_pointer() == expect
}
fn test_ipv6_addr_with_scope() {
addr := netaddr.Ipv6Addr.from_string('fe80::896:7aff:e87:4ae3%lan0')!
assert addr.zone_id as string == 'lan0'
assert addr.str() == 'fe80::896:7aff:e87:4ae3%lan0'
assert netaddr.Ipv6Addr.from_string('fe80::896:7aff:e87:4ae3')!
.with_scope('1')!
.str() == 'fe80::896:7aff:e87:4ae3%1'
}
fn test_ipv6_addr_is_ipv4_compat() {
assert !netaddr.Ipv6Addr.from_string('::')!.is_ipv4_compat()
assert !netaddr.Ipv6Addr.from_string('::1')!.is_ipv4_compat()
assert netaddr.Ipv6Addr.from_string('::192.168.0.3')!.is_ipv4_compat()
}
fn test_ipv6_addr_is_ipv4_mapped() {
assert netaddr.Ipv6Addr.from_string('::ffff:cb00:715a')!.is_ipv4_mapped()
assert !netaddr.Ipv6Addr.from_string('::fff:cb00:715a')!.is_ipv4_mapped()
}
fn test_ipv6_addr_ipv4() {
assert netaddr.Ipv6Addr.from_string('::ffff:cb00:715a')!.ipv4()!.str() == '203.0.113.90'
}
fn test_ipv6_addr_six_to_four() {
assert netaddr.Ipv6Addr.from_string('2002:c001:0203::')!.six_to_four()!.str() == '192.1.2.3'
assert netaddr.Ipv6Addr.from_string('2002:09fe:fdfc::')!.six_to_four()!.str() == '9.254.253.252'
}
fn test_ipv6_addr_teredo() {
teredo := netaddr.Ipv6Addr.from_string('2001:0000:4136:e378:8000:63bf:3fff:fdd2')!.teredo()!
assert teredo.server.str() == '65.54.227.120'
assert teredo.flags == 0x8000
assert teredo.port == 40_000
assert teredo.client.str() == '192.0.2.45'
}
fn test_teredo_addr_ipv6() {
teredo := netaddr.TeredoAddr{
server: netaddr.Ipv4Addr.from_string('65.54.227.120')!
flags: 0x8000
port: 40_000
client: netaddr.Ipv4Addr.from_string('192.0.2.45')!
}
assert teredo.ipv6().str() == '2001:0:4136:e378:8000:63bf:3fff:fdd2'
}
fn test_ipv6_addr_tests() {
addr := netaddr.Ipv6Addr.from_string('fe80::d08e:6658:38bd:6391')!
assert !addr.is_ipv4_mapped()
assert !addr.is_ipv4_compat()
assert !addr.is_site_local()
assert !addr.is_unique_local()
assert addr.is_link_local()
assert !addr.is_loopback()
assert !addr.is_multicast()
assert addr.is_unicast()
assert addr.is_private()
assert !addr.is_global()
assert !addr.is_reserved()
assert !addr.is_unspecified()
}
fn test_ipv6_is_netmask_is_hostmask() {
assert netaddr.Ipv6Addr.from_string('ffff:ffff:ffff:ffff:ffff:ffff:0000:0000')!.is_netmask()
assert !netaddr.Ipv6Addr.from_string('ffff:ffff:ffff:ffff:ffff:ffff:0000:ffff')!.is_netmask()
assert netaddr.Ipv6Addr.from_string('::ffff:ffff:ffff:ffff')!.is_hostmask()
assert !netaddr.Ipv6Addr.from_string('::2a:ffff:ffff:ffff:ffff')!.is_hostmask()
}
fn test_ipv6_net() {
net := netaddr.Ipv6Net.from_string('fe80::/64')!
assert net.str() == 'fe80::/64'
assert net.network_address.str() == 'fe80::'
assert net.network_mask.str() == 'ffff:ffff:ffff:ffff::'
assert net.host_mask.str() == '::ffff:ffff:ffff:ffff'
assert net.broadcast_address.str() == 'fe80::ffff:ffff:ffff:ffff'
assert net.host_address == none
assert net.prefix_len == 64
}
fn test_ipv6_net_new() {
addr := netaddr.Ipv6Addr.from_string('fe80::')!
net := netaddr.Ipv6Net.new(addr, 64)!
assert net.str() == 'fe80::/64'
assert net.network_address.str() == 'fe80::'
assert net.network_mask.str() == 'ffff:ffff:ffff:ffff::'
assert net.host_mask.str() == '::ffff:ffff:ffff:ffff'
assert net.broadcast_address.str() == 'fe80::ffff:ffff:ffff:ffff'
assert net.host_address == none
assert net.prefix_len == 64
}
fn test_ipv6_net_from_string() {
assert netaddr.Ipv6Net.from_string('fe80:ffff::/64')!.str() == 'fe80:ffff::/64'
assert netaddr.Ipv6Net.from_string('fe80:ffff::/ffff:ffff:ffff:ffff::')!.str() == 'fe80:ffff::/64'
assert netaddr.Ipv6Net.from_string('fe80:ffff::/::ffff:ffff:ffff:ffff')!.str() == 'fe80:ffff::/64'
}
fn test_ipv6_net_format() {
net := netaddr.Ipv6Net.from_string('fe80:ffff::/64')!
assert net.format(.compact) == 'fe80:ffff::/64'
assert net.format(.with_prefix_len) == 'fe80:ffff::/64'
assert net.format(.with_network_mask) == 'fe80:ffff::/ffff:ffff:ffff:ffff::'
assert net.format(.with_host_mask) == 'fe80:ffff::/::ffff:ffff:ffff:ffff'
assert net.format(.verbose) == 'fe80:ffff:0000:0000:0000:0000:0000:0000/64'
assert net.format(.verbose | .with_prefix_len) == 'fe80:ffff:0000:0000:0000:0000:0000:0000/64'
assert net.format(.verbose | .with_network_mask) == 'fe80:ffff:0000:0000:0000:0000:0000:0000/ffff:ffff:ffff:ffff:0000:0000:0000:0000'
assert net.format(.verbose | .with_host_mask) == 'fe80:ffff:0000:0000:0000:0000:0000:0000/0000:0000:0000:0000:ffff:ffff:ffff:ffff'
}
fn test_ipv6_net_next() {
net := netaddr.Ipv6Net.from_string('fe80::/64')!
mut addrs := []netaddr.Ipv6Addr{}
limit := 5
for i, addr in net {
if i >= limit {
break
}
addrs << addr
}
assert addrs[0].str() == 'fe80::'
assert addrs[1].str() == 'fe80::1'
assert addrs[2].str() == 'fe80::2'
assert addrs[3].str() == 'fe80::3'
}
fn test_ipv6_net_subnets() {
net := netaddr.Ipv6Net.from_string('fe80::/48')!
subnets := net.subnets(64)!
mut networks := []netaddr.Ipv6Net{}
limit := 5
for i, subnet in subnets {
if i >= limit {
break
}
networks << subnet
}
assert networks[0].str() == 'fe80::/64'
assert networks[1].str() == 'fe80:0:0:1::/64'
assert networks[2].str() == 'fe80:0:0:2::/64'
assert networks[3].str() == 'fe80:0:0:3::/64'
}
fn test_ipv6_net_supernet() {
net := netaddr.Ipv6Net.from_string('fe80:0:0:3::/64')!
assert net.supernet(48)!.str() == 'fe80::/48'
}

188
tests/ip_test.v Normal file
View File

@ -0,0 +1,188 @@
import netaddr
fn test_ipv4_addr_from_string() {
assert netaddr.Ipv4Addr.from_string('203.0.113.1')!.str() == '203.0.113.1'
}
fn test_ipv4_addr_from_u32() {
assert netaddr.Ipv4Addr.from_u32(0).u8_array() == []u8{len: 4}
assert netaddr.Ipv4Addr.from_u32(0).u8_array_fixed() == [4]u8{}
assert netaddr.Ipv4Addr.from_u32(u32(2886733829)).str() == '172.16.16.5'
}
fn test_ipv4_addr_tests() {
addr := netaddr.Ipv4Addr.from_string('203.0.113.1')!
assert !addr.is_link_local()
assert !addr.is_loopback()
assert !addr.is_multicast()
assert addr.is_unicast()
assert !addr.is_shared()
assert addr.is_private()
assert !addr.is_global()
assert !addr.is_reserved()
assert !addr.is_unspecified()
}
fn test_ipv4_addr_ipv6() {
addr := netaddr.Ipv4Addr.from_string('203.0.113.90')!
assert addr.ipv6().str() == '::ffff:203.0.113.90'
assert addr.ipv6(kind: .compat).str() == '::203.0.113.90'
}
fn test_ipv4_ipv6_addr_arr() {
mut addrs := []netaddr.IpAddr{}
addrs << netaddr.Ipv4Addr.from_string('203.0.113.90')!
addrs << netaddr.Ipv6Addr.from_string('::1')!
assert (addrs[0] as netaddr.Ipv4Addr).str() == '203.0.113.90'
assert (addrs[1] as netaddr.Ipv6Addr).str() == '::1'
}
fn test_ipv4_net_compare() {
assert netaddr.Ipv4Net.from_string('10.0.0.0/24')! < netaddr.Ipv4Net.from_string('10.10.0.0/24')!
}
fn test_ipv4_net() {
net := netaddr.Ipv4Net.from_string('198.51.100.0/24')!
assert net.str() == '198.51.100.0/24'
assert net.prefix_len == 24
assert net.network_address.str() == '198.51.100.0'
assert net.network_mask.str() == '255.255.255.0'
assert net.host_mask.str() == '0.0.0.255'
assert net.broadcast_address.str() == '198.51.100.255'
assert net.capacity() == 256
assert !net.is_global()
}
fn test_ipv4_net_from_string() {
net1 := netaddr.Ipv4Net.from_string('198.51.100.0/24')!
net2 := netaddr.Ipv4Net.from_string('198.51.100.0/255.255.255.0')!
net3 := netaddr.Ipv4Net.from_string('198.51.100.0/0.0.0.255')!
assert net1.str() == '198.51.100.0/24'
assert net2.str() == '198.51.100.0/24'
assert net3.str() == '198.51.100.0/24'
assert net1.host_address == none
assert net2.host_address == none
assert net3.host_address == none
assert net3.host_address as netaddr.Ipv4Addr == netaddr.Ipv4Addr{}
assert (net3.host_address as netaddr.Ipv4Addr).u8_array_fixed() == [4]u8{}
net4 := netaddr.Ipv4Net.from_string('198.51.100.12/24')!
net5 := netaddr.Ipv4Net.from_string('198.51.100.12/255.255.255.0')!
net6 := netaddr.Ipv4Net.from_string('198.51.100.12/0.0.0.255')!
assert net4.str() == '198.51.100.0/24'
assert net5.str() == '198.51.100.0/24'
assert net6.str() == '198.51.100.0/24'
assert (net4.host_address as netaddr.Ipv4Addr).str() == '198.51.100.12'
assert (net5.host_address as netaddr.Ipv4Addr).str() == '198.51.100.12'
assert (net6.host_address as netaddr.Ipv4Addr).str() == '198.51.100.12'
net7 := netaddr.Ipv4Net.from_string('172.16.16.6')!
assert net7.str() == '172.16.16.6/32'
assert net7.host_address == none
}
fn test_ipv4_net_from_u32() {
net1 := netaddr.Ipv4Net.from_u32(3405803776, 24)!
net2 := netaddr.Ipv4Net.from_u32(3405803788, 24)!
assert net1.str() == '203.0.113.0/24'
assert net1.host_address == none
assert net2.str() == '203.0.113.0/24'
assert (net2.host_address as netaddr.Ipv4Addr).u32() == u32(3405803788)
}
fn test_ipv4_net_host_bits() {
net := netaddr.Ipv4Net.from_string('10.0.10.2/29')!
assert net.network_address.str() == '10.0.10.0'
assert (net.host_address as netaddr.Ipv4Addr).str() == '10.0.10.2'
}
fn test_ipv4_net_0() {
net := netaddr.Ipv4Net.from_string('0.0.0.0/0')!
assert net.str() == '0.0.0.0/0'
assert net.prefix_len == 0
assert net.network_address.str() == '0.0.0.0'
assert net.network_mask.str() == '0.0.0.0'
assert net.host_mask.str() == '255.255.255.255'
assert net.broadcast_address.str() == '255.255.255.255'
assert net.host_address == none
assert net.capacity() == u64(max_u32) + 1
}
fn test_ipv4_net_255() {
net := netaddr.Ipv4Net.from_string('255.255.255.255/32')!
assert net.str() == '255.255.255.255/32'
assert net.prefix_len == 32
assert net.network_address.str() == '255.255.255.255'
assert net.network_mask.str() == '255.255.255.255'
assert net.host_mask.str() == '0.0.0.0'
assert net.broadcast_address.str() == '255.255.255.255'
assert net.host_address == none
assert net.capacity() == 1
}
fn test_ipv4_net_next() {
net := netaddr.Ipv4Net.from_string('10.0.10.128/30')!
mut addrs := []netaddr.Ipv4Addr{}
for addr in net {
addrs << addr
}
assert addrs[0].str() == '10.0.10.128'
assert addrs[1].str() == '10.0.10.129'
assert addrs[2].str() == '10.0.10.130'
assert addrs[3].str() == '10.0.10.131'
}
fn test_ipv4_net_subnets() {
net := netaddr.Ipv4Net.from_string('10.0.10.0/24')!
subnets := net.subnets(26)!
mut networks := []netaddr.Ipv4Net{}
for subnet in subnets {
networks << subnet
}
assert networks[0].str() == '10.0.10.0/26'
assert networks[1].str() == '10.0.10.64/26'
assert networks[2].str() == '10.0.10.128/26'
assert networks[3].str() == '10.0.10.192/26'
}
fn test_ipv4_net_nth() {
net := netaddr.Ipv4Net.from_string('10.0.10.0/24')!
assert net.nth(-2)!.str() == '10.0.10.254'
assert net.nth(-1)!.str() == '10.0.10.255'
assert net.nth(0)!.str() == '10.0.10.0'
assert net.nth(1)!.str() == '10.0.10.1'
assert (net.nth(99999) or { netaddr.Ipv4Addr{} }).str() == '0.0.0.0'
}
fn test_ipv4_net_supernet() {
net := netaddr.Ipv4Net.from_string('10.129.10.0/24')!
supernet := net.supernet(10)!
assert supernet.str() == '10.128.0.0/10'
}
fn test_ipv4_net_is_subnet_of() {
net1 := netaddr.Ipv4Net.from_string('10.10.0.0/16')!
net2 := netaddr.Ipv4Net.from_string('10.10.0.0/24')!
assert net2.is_subnet_of(net1)
}
fn test_ipv4_net_is_supernet_of() {
net1 := netaddr.Ipv4Net.from_string('10.10.0.0/16')!
net2 := netaddr.Ipv4Net.from_string('10.10.0.0/24')!
net3 := netaddr.Ipv4Net.from_string('172.16.16.0/24')!
assert net1.is_supernet_of(net2)
assert !net1.is_supernet_of(net3)
}
fn test_ipv4_net_first_last() {
net1 := netaddr.Ipv4Net.from_string('10.0.0.0/24')!
net2 := netaddr.Ipv4Net.from_string('10.0.0.0/30')!
net3 := netaddr.Ipv4Net.from_string('10.0.0.0/31')!
net4 := netaddr.Ipv4Net.from_string('10.0.0.0/32')!
assert net1.first().str() == '10.0.0.1'
assert net1.last().str() == '10.0.0.254'
assert net2.first().str() == '10.0.0.1'
assert net2.last().str() == '10.0.0.2'
assert net3.first().str() == '10.0.0.0'
assert net3.last().str() == '10.0.0.1'
assert net4.first().str() == '10.0.0.0'
assert net4.last().str() == '10.0.0.0'
}

7
v.mod Normal file
View File

@ -0,0 +1,7 @@
Module {
name: 'netaddr'
description: 'Network address processing library for V'
version: '0.1.0'
license: 'LGPL-3.0-or-later'
dependencies: []
}