python-iplib_1.1.orig/bin/cidrinfo.py0000755000000000000000000000205510760353567020114 0ustar00usergroup00000000000000#!/usr/bin/env python # # CIDRInfo # Shows informations about a CIDR address. # # Copyright 2001-2006 Davide Alberani # # This code is released under the GPL license. # import iplib, sys, os CALL_NAME = os.path.basename(sys.argv[0]) APP_NAME='CIDRInfo' VERSION='0.2' MYEMAIL='Davide Alberani ' HELP = """ %s Version: %s Usage: %s ip_address/netmask Send bug reports to %s """ % (APP_NAME, VERSION, CALL_NAME, MYEMAIL) if len(sys.argv[1:]) != 1: sys.stderr.write('Only one argument is required.\n') print HELP sys.exit(2) address = sys.argv[1] try: cidr = iplib.CIDR(address) except ValueError: sys.stderr.write('%s: invalid CIDR address.\n' % address) print HELP sys.exit(3) print 'CIDR:', str(cidr) print 'first usable IP address:', str(cidr.get_first_ip()) print 'last usable IP address:', str(cidr.get_last_ip()) print 'number of usable IP addresses:', str(cidr.get_ip_number()) print 'network address:', str(cidr.get_network_ip()) print 'broadcast address:', str(cidr.get_broadcast_ip()) python-iplib_1.1.orig/bin/ipconv.py0000755000000000000000000000427210760353567017620 0ustar00usergroup00000000000000#!/usr/bin/env python # # IPConv # Convert among ip address notations. # # Copyright 2001-2006 Davide Alberani # # This code is released under the GPL license. # import iplib, sys, getopt, os CALL_NAME = os.path.basename(sys.argv[0]) APP_NAME='IPConv' VERSION='0.6' MYEMAIL='Davide Alberani ' HELP = """ %s Version: %s Usage: %s [OPTIONS] ip_address Options: -o output only in the specified notation (e.g.: dot|hex|bin|dec|oct). -i the input is in the given notation (otherwise it's autodetected). Send bug reports to %s """ % (APP_NAME, VERSION, CALL_NAME, MYEMAIL) try: optlist, args = getopt.getopt(sys.argv[1:], 'ho:i:', ['help', 'output=', 'input=']) except getopt.error: print HELP sys.exit(1) if len(args) != 1: sys.stderr.write('Only one argument is required.\n') print HELP sys.exit(2) outp = '' inp = '' for opt in optlist: if opt[0] == '-h' or opt[0] == '--help': print HELP sys.exit(0) elif opt[0] == '-o' or opt[0] == '--output': outp = opt[1] elif opt[0] == '-i' or opt[0] == '--input': inp = opt[1] ip = args[0] if not inp: inp = iplib.detect(ip) if not outp and inp: print ' notation autodetected as: "%s"' % iplib.p_notation(inp) if inp == iplib.IP_UNKNOWN: sys.stderr.write('unable to autodetect the notation of "%s"' % ip) print HELP sys.exit(4) try: myip = iplib.IPv4Address(ip, notation=inp) except ValueError: sys.stderr.write('%s address is not in notation %s.\n' % (ip, iplib.p_notation(inp))) print HELP sys.exit(4) if outp == 'dot': print myip.get_dot() elif outp == 'hex': print myip.get_hex() elif outp == 'bin': print myip.get_bin() elif outp == 'dec': print myip.get_dec() elif outp == 'oct': print myip.get_oct() elif not outp: print 'Dotted decimal :', myip.get_dot() print 'Hexdecimal :', myip.get_hex() print 'Octal :', myip.get_oct() print 'Binary :', myip.get_bin() print 'Decimal :', myip.get_dec() else: sys.stderr.write('%s: invalid notation.\n' % outp) print HELP sys.exit(5) sys.exit(0) python-iplib_1.1.orig/bin/nmconv.py0000755000000000000000000000430210760353567017614 0ustar00usergroup00000000000000#!/usr/bin/env python # # NMConv # Convert among netmask notations. # # Copyright 2001-2006 Davide Alberani # # This code is released under the GPL license. # import iplib, sys, getopt, os CALL_NAME = os.path.basename(sys.argv[0]) APP_NAME='NMConv' VERSION='0.6' MYEMAIL='Davide Alberani ' HELP = """ %s Version: %s Usage: %s [OPTIONS] netmask Options: -o output only in the specified notation (e.g.: dot|hex|bin|dec|oct). -i the input is in the given notation (otherwise it's autodetected). Send bug reports to %s """ % (APP_NAME, VERSION, CALL_NAME, MYEMAIL) try: optlist, args = getopt.getopt(sys.argv[1:], 'ho:i:', ['help', 'output=', 'input=']) except getopt.error: print HELP sys.exit(1) if len(args) != 1: sys.stderr.write('Only one argument is required.\n') print HELP sys.exit(2) outp = '' inp = '' for opt in optlist: if opt[0] == '-h' or opt[0] == '--help': print HELP sys.exit(0) elif opt[0] == '-o' or opt[0] == '--output': outp = opt[1] elif opt[0] == '-i' or opt[0] == '--input': inp = opt[1] nm = args[0] if nm and nm[0] == '/': nm = nm[1:] if not inp: inp = iplib.detect_nm(nm) if not outp and inp: print ' notation autodetected as: "%s"' % iplib.p_notation(inp) if inp == iplib.IP_UNKNOWN: sys.stderr.write('unable to autodetect the notation of "%s"' % nm) print HELP sys.exit(4) if outp: try: print iplib.convert_nm(nm, notation=outp, inotation=inp) except ValueError: sys.stderr.write(nm + ' netmask is not in ' + iplib.p_notation(inp) + \ ' notation or cannot be converted to ' + \ str(outp) + '.\n') print HELP sys.exit(4) else: for notation in iplib.NOTATION_MAP.keys(): if notation == iplib.NM_UNKNOWN: continue try: print iplib.NOTATION_MAP[notation][0] + ': ' + \ iplib.convert_nm(nm, notation=notation, inotation=inp) except ValueError: sys.stderr.write('%s: invalid netmask.\n' % nm) print HELP sys.exit(4) sys.exit(0) python-iplib_1.1.orig/docs/CREDITS.txt0000644000000000000000000000055210760353567017760 0ustar00usergroup00000000000000 CREDITS ======= I want to thank: - Jeffrey Miller for a bug comparing CIDR addresses for inclusion. - Nicola Novello, for a patch to support CIDR objects in the is_valid_ip() method of the CIDR class. - Matias Hermanrud Fjeld, for a patch to implement iterations over CIDR objects. - Lars Erik Gullerud, for the bug report about the /31 netmask. python-iplib_1.1.orig/docs/Changelog.txt0000644000000000000000000000211310760353567020545 0ustar00usergroup00000000000000 version 1.1 (13 feb 2008) - fixed a bug comparing CIDRs for inclusion. version 1.0 (23 may 2006) - iteration over CIDR object. - comparison operators for addresses, netmasks and cidr objects. - augmented and reflected arithmetic operations for IP addresses. - notation autodetection now firstly check if the given IP/netmask is in bits notation (for netmasks) or in decimal notation (for IPs). - cleaned the code and dropped compatibility with Python 1.5 (at least python 2.3 is required. - renamed scripts adding ".py" extension. - used boolean values instead of 0 and 1. - faster conversion operators. - changed the "iformat" argument of convert and convert_nm functions to "inotation". - added some properties for addresses, netmasks and cidr objects. - CIDR.is_valid_ip method now manage the /31 netmask case more logically. - summing/subtracting addresses is more cleaner. - fixed some typos. - improved the test suite. version 0.9 (16 oct 2005) - support for CIDR object in the is_valid_ip() method of the CIDR class. version 0.8 (15 feb 2005) - support for /31 netmask. python-iplib_1.1.orig/docs/GPL.txt0000644000000000000000000004311010760353567017302 0ustar00usergroup00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. 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 convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This 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 Library General Public License instead of this License. python-iplib_1.1.orig/docs/INSTALL.txt0000644000000000000000000000101210760353567017761 0ustar00usergroup00000000000000 Requirements ------------ * Python version 2.3 or later. Install ------- Type, as root user: python ./setup.py install If it doesn't work, copy the 'iplib.py' module it in your local site-packages directory (i.e. /usr/local/lib/python2.4/site-packages/ or /usr/lib/python2.4/site-packages/ if you're using Python 2.4). Copy the example scripts 'ipconv.py', 'nmconv.py' and 'cidrinfo.py' from the ./bin directory to a directory included in your PATH environment variable (/usr/bin/ or /usr/local/bin/). python-iplib_1.1.orig/docs/README.iplib0000644000000000000000000001255710760353567020110 0ustar00usergroup00000000000000 The iplib module ---------------- The iplib module contains many functions, classes and constants useful to manage IP addresses and netmasks. Functions --------- * These functions always return True or False (never raise exceptions) and can be called with any kind of arguments (integers, strings and objects with a __str__() method which returns a suitable string): is_dot(ip): Return True if the IP address is in dotted decimal notation. is_hex(ip): Return True if the IP address is in hexadecimal notation. is_bin(ip): Return True if the IP address is in binary notation. is_oct(ip): Return True if the IP address is in octal notation. is_dec(ip): Return True if the IP address is in decimal notation. is_dot_nm(nm): Return True if the netmask is in dotted decimal notatation. is_hex_nm(nm): Return True if the netmask is in hexadecimal notatation. is_bin_nm(nm): Return True if the netmask is in binary notatation. is_oct_nm(nm): Return True if the netmask is in octal notatation. is_dec_nm(nm): Return True if the netmask is in decimal notatation. is_bits_nm(nm): Return True if the netmask is in bits notatation. is_wildcard_nm(nm): Return True if the netmask is in wildcard bits notatation. * Functions to detect IP/netmask notation; return IP_UNKNOWN/NM_UNKNOWN if the IP/netmask notation is not detected: detect(ip): Try to detect the notation of an IP address. detect_nm(nm): Try to detect the notation of a netmask. p_detect(ip) and p_detect_nm(nm): detect the notation of an IP address (or netmask) and return a nice string ('unknown' if it's not detected). is_notation(ip, notation) and is_notation_nm(nm, notation): return True if the given IP address (or netmask) is in the specified notation. * Function to convert IP/netmask; can raise a ValueError exception: convert(ip, notation=IP_DOT, inotation=IP_UNKNOWN) and convert_nm(nm, notation=IP_DOT, inotation=IP_UNKNOWN): Convert the given IP address (or netmask) to the given notation; the 'notation' argument set the notation of the output; the 'inotation' argument force the input to be considered as an address in the specified notation. When the IP address (or netmask) is an integer, the inotation argument is assumed to be IP_DEC (if not set otherwise). Classes ------- IPv4Address: IPv4Address(ip, notation=IP_UNKNOWN): This class represents an IPv4 Internet address. An IPv4Address object can be used to sum or subtract two IP address; the second argument can also be an integer, so that, if you want to know what's the 1000th IP address after 127.0.0.1, you can: >>> import iplib >>> ip = iplib.IPv4Address('127.0.0.1') >>> ip + 1000 It's also possible to compare two IP addresses (the same is true for netmasks); e.g.: >>> iplib.IPv4Address('127.0.0.1') < iplib.IPv4Address('127.0.0.4') 1 For both IPv4Address and IPv4NetMask object you can force the notation with the 'notation' option; e.g.: >>> iplib.IPv4Address('24323', iplib.IP_OCT) # that's equivalent to: >>> iplib.IPv4Address('24323', 'oct') # and: >>> iplib.IPv4Address('24323', 'octal') IPv4NetMask: IPv4NetMask(nm, notation=IP_UNKNOWN): This class represents an IPv4 Internet netmask. CIDR: CIDR(ip, netmask=None): The representation of a Classless Inter-Domain Routing (CIDR) address. From objects instance of this class, you can retrieve informations about the number of usable IP addresses, the first and the last usable address, the broadcast and the netword address. The netmask can be omitted, if the ip argument is a string 'ip/nm'; e.g.: >>> cidr = iplib.CIDR('127.0.0.1', '8') # is equivalent to: >>> cidr = iplib.CIDR('127.0.0.1/8') Using the is_valid_ip(self, ip) method you can guess if the provided IP address is amongst the usable addresses; e.g.: >>> cidr = iplib.CIDR('127.0.0.1/8') >>> cidr.is_valid_ip('127.4.5.6') 1 Constants --------- * THe following constants are used to define IP/netmask notations: IP_DOT and NM_DOT: an IP address (or netmask) in dotted decimal notation (e.g.: 192.168.0.42). IP_HEX and NM_HEX: hexadecimal notation (0xC0A8002A). IP_BIN and NM_BIN: binary notation (11000000101010000000000000101010). IP_OCT and NM_OCT: octal notation (030052000052). IP_DEC and NM_DEC: decimal notation (3232235562). NM_BITS: netmask in bits notation (24). NM_WILDCARD: netmask in wildcard bits notation (0.0.0.255). IP_UNKNOWN and NM_UNKNOWN: an IP address (or netmask) in a unknown notation. NOTATION_MAP: a dictionary that maps notations with a list of strings that can be used instead of the IP_* and NM_* constants. E.g.: you can call the convert() function in these two equivalent ways: iplib.convert('192.168.0.42', notation=iplib.IP_HEX) iplib.convert('192.168.0.42', 'hex') The following strings can be used instead of constants: 'binary', 'bin': IP_BIN/NM_BIN 'octal', 'oct': IP_OCT/NM_OCT 'decimal', 'dec': IP_DEC/NM_DEC 'bits', 'bit', 'cidr': NM_BITS 'wildcard bits', 'wildcard': NM_WILDCARD 'unknown', 'unk': IP_UNKNOWN/NM_UNKNOWN VALID_NETMASKS: a dictionary that maps valid netmask in bits notation with their values in decimal notation. python-iplib_1.1.orig/docs/README.scripts0000644000000000000000000000547510760353567020501 0ustar00usergroup00000000000000 iplib scripts ------------- ipconv.py --------- This script show hot to use the IPv4Address class of the iplib module. Given an IP address, show the IP in various notations. Requires one argument: the IP address. Options: -i notation: force the input to be considered in the given notation, otherwise it's autodetected. -o notation: show the address only in the given notation. Valid notations are: 'dot', 'hex', 'bin', 'oct', 'dec'. nmconv.py --------- This script show hot to use the convert_nm() function of the iplib module. nmconv.py takes the same arguments and options of the ipconv.py script (additional valid notations are: 'bits', 'wildcard'). cidrinfo.py ----------- cidrinfo.py takes only one argument, a 'ip/netmask' CIDR notation, and returns some informations about this subnet; e.g.: $ cidrinfo.py 127.0.0.1/8 CIDR: 127.0.0.1/255.0.0.0 first usable IP address: 127.0.0.1 last usable IP address: 127.255.255.254 number of usable IP addresses: 16777214 network address: 127.0.0.0 broadcast address: 127.255.255.255 examples (ipconv.py and nmconv.py) ---------------------------------- $ ipconv.py 1.2.3.4 notation autodetected as: "dotted decimal" Dotted decimal : 1.2.3.4 Hexdecimal : 0x1020304 Octal : 0100401404 Binary : 00000001000000100000001100000100 Decimal : 16909060 $ ipconv.py 0x234234 notation autodetected as: "hexadecimal" Dotted decimal : 0.35.66.52 Hexdecimal : 0x234234 Octal : 010641064 Binary : 00000000001000110100001000110100 Decimal : 2310708 $ ipconv.py 0234234 notation autodetected as: "octal" Dotted decimal : 0.1.56.156 Hexdecimal : 0x1389C Octal : 0234234 Binary : 00000000000000010011100010011100 Decimal : 80028 # Force the input to be considered as a decimal. $ ipconv.py -i dec 234 Dotted decimal : 0.0.0.234 Hexdecimal : 0xEA Octal : 0352 Binary : 00000000000000000000000011101010 Decimal : 234 # Only returns a given notation (hexadecimal in the example). $ ipconv.py -o hex 127.0.0.1 0x7F000001 $ nmconv.py 16 notation autodetected as: "bits" dotted decimal: 255.255.0.0 hexadecimal: 0xFFFF0000 binary: 11111111111111110000000000000000 octal: 037777600000 decimal: 4294901760 bits: 16 wildcard bits: 0.0.255.255 $ nmconv.py 255.0.0.0 notation autodetected as: "dotted decimal" dotted decimal: 255.0.0.0 hexadecimal: 0xFF000000 binary: 11111111000000000000000000000000 octal: 037700000000 decimal: 4278190080 bits: 8 wildcard bits: 0.255.255.255 $ nmconv.py 0.0.0.63 notation autodetected as: "wildcard bits" dotted decimal: 255.255.255.192 hexadecimal: 0xFFFFFFC0 binary: 11111111111111111111111111000000 octal: 037777777700 decimal: 4294967232 bits: 26 wildcard bits: 0.0.0.63 $ nmconv.py -o dec 0.0.0.63 4294967232 python-iplib_1.1.orig/docs/README.txt0000644000000000000000000000155110760353567017620 0ustar00usergroup00000000000000 iplib ----- You can use this Python module (and the scripts 'ipconv.py', 'nmconv.py' and 'cidrinfo.py') to convert amongst many different notations and to manage couples of address/netmask in the CIDR notation. How to use ---------- To learn how to use the 'iplib' Python module, see 'README.iplib'; the example scripts are described in 'README.scripts'. License ------- This code is release under the GPL license. Disclaimer ---------- It's YOUR fault, not MINE! :-) Author and contacts ------------------- Davide Alberani e-mail: da@erlug.linux.it Iplib pages: http://erlug.linux.it/~da//soft/iplib/ my homepage: http://erlug.linux.it/~da/ ICQ UIN: 83641305 (nick 'Mad77') (very rarely used) Jabber ID: alberanid@jabber.linux.it (very rarely used) PGP KeyID: 0x465BFD47 (the key is available in my homepage) python-iplib_1.1.orig/docs/TODO.txt0000644000000000000000000000034310760353567017426 0ustar00usergroup00000000000000 iplib TODO - support for IPv6. - a hierarchy of exceptions. - cleanup the code (it's ugly! :) - improve performances. - better documentation. - some pretty-printing functions. - the CIDR class can provide more information. python-iplib_1.1.orig/iplib.py0000644000000000000000000006701710760353567016654 0ustar00usergroup00000000000000""" iplib module. The representation of IPv4 addresses and netmasks. You can use this module to convert amongst many different notations and to manage couples of address/netmask in the CIDR notation. Copyright 2001-2008 Davide Alberani 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ __version__ = '1.1' from types import IntType, LongType _IntegerTypes = (IntType, LongType) # Notation types (with an example in the comment). # You can use these constants when you have to specify a notation style. IP_UNKNOWN = NM_UNKNOWN = 0 IP_DOT = NM_DOT = 1 # 192.168.0.42 IP_HEX = NM_HEX = 2 # 0xC0A8002A IP_BIN = NM_BIN = 3 # 030052000052 IP_OCT = NM_OCT = 4 # 11000000101010000000000000101010 IP_DEC = NM_DEC = 5 # 3232235562 NM_BITS = 6 # 26 NM_WILDCARD = 7 # 0.0.0.63 # Map notations with one or more strings. # You can use these constant strings when you have to specify a notation # style, instead of using numeric values. NOTATION_MAP = { IP_DOT: ('dotted decimal', 'dotted', 'quad', 'dot', 'dotted quad'), IP_HEX: ('hexadecimal', 'hex'), IP_BIN: ('binary', 'bin'), IP_OCT: ('octal', 'oct'), IP_DEC: ('decimal', 'dec'), NM_BITS: ('bits', 'bit', 'cidr'), NM_WILDCARD: ('wildcard bits', 'wildcard'), IP_UNKNOWN: ('unknown', 'unk') } _NOTATION_KEYS = dict([(key, key) for key in NOTATION_MAP.keys()]) for key, values in NOTATION_MAP.items(): for value in values: _NOTATION_KEYS[value] = key def _get_notation(notation): """Given a numeric value or string value, returns one in IP_DOT, IP_HEX, IP_BIN, etc., or None if unable to convert to the internally used numeric convention.""" return _NOTATION_KEYS.get(notation, None) def p_notation(notation): """Return a string representing the given notation.""" return NOTATION_MAP[_get_notation(notation) or IP_UNKNOWN][0] # This dictionary maps NM_BITS to NM_DEC values. # NOTE: /31 is a valid netmask; see RFC3021 (courtesy of Lars Erik Gullerud). VALID_NETMASKS = {0: 0L, 1: 2147483648L, 2: 3221225472L, 3: 3758096384L, 4: 4026531840L, 5: 4160749568L, 6: 4227858432L, 7: 4261412864L, 8: 4278190080L, 9: 4286578688L, 10: 4290772992L, 11: 4292870144L, 12: 4293918720L, 13: 4294443008L, 14: 4294705152L, 15: 4294836224L, 16: 4294901760L, 17: 4294934528L, 18: 4294950912L, 19: 4294959104L, 20: 4294963200L, 21: 4294965248L, 22: 4294966272L, 23: 4294966784L, 24: 4294967040L, 25: 4294967168L, 26: 4294967232L, 27: 4294967264L, 28: 4294967280L, 29: 4294967288L, 30: 4294967292L, 31: 4294967294L, 32: 4294967295L} _NETMASKS_VALUES = VALID_NETMASKS.values() _NETMASKS_INV = dict([(value, key) for key, value in VALID_NETMASKS.items()]) # - Functions used to check if an address or a netmask is in a given notation. def is_dot(ip): """Return true if the IP address is in dotted decimal notation.""" octets = str(ip).split('.') if len(octets) != 4: return False for i in octets: try: val = long(i) except ValueError: return False if val > 255 or val < 0: return False return True def is_hex(ip): """Return true if the IP address is in hexadecimal notation.""" try: dec = long(str(ip), 16) except (TypeError, ValueError): return False if dec > 0xFFFFFFFFL or dec < 0: return False return True def is_bin(ip): """Return true if the IP address is in binary notation.""" try: ip = str(ip) if len(ip) != 32: return False dec = long(ip, 2) except (TypeError, ValueError): return False if dec > 4294967295L or dec < 0: return False return True def is_oct(ip): """Return true if the IP address is in octal notation.""" try: dec = long(str(ip), 8) except (TypeError, ValueError): return False if dec > 037777777777L or dec < 0: return False return True def is_dec(ip): """Return true if the IP address is in decimal notation.""" try: dec = long(str(ip)) except ValueError: return False if dec > 4294967295L or dec < 0: return False return True def _check_nm(nm, notation): """Function internally used to check if the given netmask is of the specified notation.""" # Convert to decimal, and check if it's in the list of valid netmasks. _NM_CHECK_FUNCT = { NM_DOT: _dot_to_dec, NM_HEX: _hex_to_dec, NM_BIN: _bin_to_dec, NM_OCT: _oct_to_dec, NM_DEC: _dec_to_dec_long} try: dec = _NM_CHECK_FUNCT[notation](nm, check=True) except ValueError: return False if dec in _NETMASKS_VALUES: return True return False def is_dot_nm(nm): """Return true if the netmask is in dotted decimal notatation.""" return _check_nm(nm, NM_DOT) def is_hex_nm(nm): """Return true if the netmask is in hexadecimal notatation.""" return _check_nm(nm, NM_HEX) def is_bin_nm(nm): """Return true if the netmask is in binary notatation.""" return _check_nm(nm, NM_BIN) def is_oct_nm(nm): """Return true if the netmask is in octal notatation.""" return _check_nm(nm, NM_OCT) def is_dec_nm(nm): """Return true if the netmask is in decimal notatation.""" return _check_nm(nm, NM_DEC) def is_bits_nm(nm): """Return true if the netmask is in bits notatation.""" try: bits = long(str(nm)) except ValueError: return False if bits > 32 or bits < 0: return False return True def is_wildcard_nm(nm): """Return true if the netmask is in wildcard bits notatation.""" try: dec = 0xFFFFFFFFL - _dot_to_dec(nm, check=True) except ValueError: return False if dec in _NETMASKS_VALUES: return True return False # - Functions used to convert various notation to/from decimal notation. def _dot_to_dec(ip, check=True): """Dotted decimal notation to decimal conversion.""" if check and not is_dot(ip): raise ValueError, '_dot_to_dec: invalid IP: "%s"' % ip octets = str(ip).split('.') dec = 0L dec |= long(octets[0]) << 24 dec |= long(octets[1]) << 16 dec |= long(octets[2]) << 8 dec |= long(octets[3]) return dec def _dec_to_dot(ip): """Decimal to dotted decimal notation conversion.""" first = int((ip >> 24) & 255) second = int((ip >> 16) & 255) third = int((ip >> 8) & 255) fourth = int(ip & 255) return '%d.%d.%d.%d' % (first, second, third, fourth) def _hex_to_dec(ip, check=True): """Hexadecimal to decimal conversion.""" if check and not is_hex(ip): raise ValueError, '_hex_to_dec: invalid IP: "%s"' % ip if isinstance(ip, _IntegerTypes): ip = hex(ip) return long(str(ip), 16) def _dec_to_hex(ip): """Decimal to hexadecimal conversion.""" return hex(ip)[:-1] def _oct_to_dec(ip, check=True): """Octal to decimal conversion.""" if check and not is_oct(ip): raise ValueError, '_oct_to_dec: invalid IP: "%s"' % ip if isinstance(ip, _IntegerTypes): ip = oct(ip) return long(str(ip), 8) def _dec_to_oct(ip): """Decimal to octal conversion.""" return oct(ip)[:-1] def _bin_to_dec(ip, check=True): """Binary to decimal conversion.""" if check and not is_bin(ip): raise ValueError, '_bin_to_dec: invalid IP: "%s"' % ip if isinstance(ip, _IntegerTypes): ip = str(ip) return long(str(ip), 2) def _BYTES_TO_BITS(): """Generate a table to convert a whole byte to binary. This code was taken from the Python Cookbook, 2nd edition - O'Reilly.""" the_table = 256*[None] bits_per_byte = range(7, -1, -1) for n in xrange(256): l = n bits = 8*[None] for i in bits_per_byte: bits[i] = '01'[n & 1] n >>= 1 the_table[l] = ''.join(bits) return the_table _BYTES_TO_BITS = _BYTES_TO_BITS() def _dec_to_bin(ip): """Decimal to binary conversion.""" bits = [] while ip: bits.append(_BYTES_TO_BITS[ip & 255]) ip >>= 8 bits.reverse() return ''.join(bits) or 32*'0' def _dec_to_dec_long(ip, check=True): """Decimal to decimal (long) conversion.""" if check and not is_dec(ip): raise ValueError, '_dec_to_dec: invalid IP: "%s"' % ip return long(str(ip)) def _dec_to_dec_str(ip): """Decimal to decimal (string) conversion.""" return str(ip) def _bits_to_dec(nm, check=True): """Bits to decimal conversion.""" if check and not is_bits_nm(nm): raise ValueError, '_bits_to_dec: invalid netmask: "%s"' % nm bits = long(str(nm)) return VALID_NETMASKS[bits] def _dec_to_bits(nm): """Decimal to bits conversion.""" return str(_NETMASKS_INV[nm]) def _wildcard_to_dec(nm, check=False): """Wildcard bits to decimal conversion.""" if check and not is_wildcard_nm(nm): raise ValueError, '_wildcard_to_dec: invalid netmask: "%s"' % nm return 0xFFFFFFFFL - _dot_to_dec(nm, check=False) def _dec_to_wildcard(nm): """Decimal to wildcard bits conversion.""" return _dec_to_dot(0xFFFFFFFFL - nm) # - Functions used to detect the notation of an IP address or netmask. _CHECK_FUNCT = { IP_DOT: (is_dot, is_dot_nm), IP_HEX: (is_hex, is_hex_nm), IP_BIN: (is_bin, is_bin_nm), IP_OCT: (is_oct, is_oct_nm), IP_DEC: (is_dec, is_dec_nm), NM_BITS: (lambda: False, is_bits_nm), NM_WILDCARD: (lambda: False, is_wildcard_nm) } _CHECK_FUNCT_KEYS = _CHECK_FUNCT.keys() def _is_notation(ip, notation, _isnm): """Internally used to check if an IP/netmask is in the given notation.""" notation_orig = notation notation = _get_notation(notation) if notation not in _CHECK_FUNCT_KEYS: raise ValueError, '_is_notation: unkown notation: "%s"' % notation_orig return _CHECK_FUNCT[notation][_isnm](ip) def is_notation(ip, notation): """Return true if the given address is in the given notation.""" return _is_notation(ip, notation, _isnm=False) def is_notation_nm(nm, notation): """Return true if the given netmask is in the given notation.""" return _is_notation(nm, notation, _isnm=True) def _detect(ip, _isnm): """Function internally used to detect the notation of the given IP or netmask.""" ip = str(ip) if len(ip) > 1: if ip[0:2] == '0x': if _CHECK_FUNCT[IP_HEX][_isnm](ip): return IP_HEX elif ip[0] == '0': if _CHECK_FUNCT[IP_OCT][_isnm](ip): return IP_OCT if _CHECK_FUNCT[IP_DOT][_isnm](ip): return IP_DOT elif _isnm and _CHECK_FUNCT[NM_BITS][_isnm](ip): return NM_BITS elif _CHECK_FUNCT[IP_DEC][_isnm](ip): return IP_DEC elif _isnm and _CHECK_FUNCT[NM_WILDCARD][_isnm](ip): return NM_WILDCARD elif _CHECK_FUNCT[IP_BIN][_isnm](ip): return IP_BIN return IP_UNKNOWN def detect(ip): """Detect the notation of an IP address. @param ip: the IP address. @type ip: integers, strings or object with an appropriate __str()__ method. @return: one of the IP_* constants; IP_UNKNOWN if undetected.""" return _detect(ip, _isnm=False) def detect_nm(nm): """Detect the notation of a netmask. @param nm: the netmask. @type nm: integers, strings or object with an appropriate __str()__ method. @return: one of the NM_* constants; NM_UNKNOWN if undetected.""" return _detect(nm, _isnm=True) def p_detect(ip): """Return the notation of an IP address (string).""" return NOTATION_MAP[detect(ip)][0] def p_detect_nm(nm): """Return the notation of a netmask (string).""" return NOTATION_MAP[detect_nm(nm)][0] def _convert(ip, notation, inotation, _check, _isnm): """Internally used to convert IPs and netmasks to other notations.""" inotation_orig = inotation notation_orig = notation inotation = _get_notation(inotation) notation = _get_notation(notation) if inotation is None: raise ValueError, '_convert: unknown input notation: "%s"' % \ inotation_orig if notation is None: raise ValueError, '_convert: unknown output notation: "%s"' % \ notation_orig docheck = _check or False if inotation == IP_UNKNOWN: inotation = _detect(ip, _isnm) if inotation == IP_UNKNOWN: raise ValueError, \ '_convert: unable to guess input notation or invalid value' if _check is None: docheck = True # We _always_ check this case later. if _isnm: docheck = False dec = 0L if inotation == IP_DOT: dec = _dot_to_dec(ip, docheck) elif inotation == IP_HEX: dec = _hex_to_dec(ip, docheck) elif inotation == IP_BIN: dec = _bin_to_dec(ip, docheck) elif inotation == IP_OCT: dec = _oct_to_dec(ip, docheck) elif inotation == IP_DEC: dec = _dec_to_dec_long(ip, docheck) elif _isnm and inotation == NM_BITS: dec = _bits_to_dec(ip, docheck) elif _isnm and inotation == NM_WILDCARD: dec = _wildcard_to_dec(ip, docheck) else: raise ValueError, '_convert: unknown IP/netmask notation: "%s"' % \ inotation_orig # Ensure this is a valid netmask. if _isnm and dec not in _NETMASKS_VALUES: raise ValueError, '_convert: invalid netmask: "%s"' % ip if notation == IP_DOT: return _dec_to_dot(dec) elif notation == IP_HEX: return _dec_to_hex(dec) elif notation == IP_BIN: return _dec_to_bin(dec) elif notation == IP_OCT: return _dec_to_oct(dec) elif notation == IP_DEC: return _dec_to_dec_str(dec) elif _isnm and notation == NM_BITS: return _dec_to_bits(dec) elif _isnm and notation == NM_WILDCARD: return _dec_to_wildcard(dec) else: raise ValueError, 'convert: unknown notation: "%s"' % notation_orig def convert(ip, notation=IP_DOT, inotation=IP_UNKNOWN, check=True): """Convert among IP address notations. Given an IP address, this function returns the address in another notation. @param ip: the IP address. @type ip: integers, strings or object with an appropriate __str()__ method. @param notation: the notation of the output (default: IP_DOT). @type notation: one of the IP_* constants, or the equivalent strings. @param inotation: force the input to be considered in the given notation (default the notation of the input is autodetected). @type inotation: one of the IP_* constants, or the equivalent strings. @param check: force the notation check on the input. @type check: True force the check, False force not to check and None do the check only if the inotation is unknown. @return: a string representing the IP in the selected notation. @raise ValueError: raised when the input is in unknown notation.""" return _convert(ip, notation, inotation, _check=check, _isnm=False) def convert_nm(nm, notation=IP_DOT, inotation=IP_UNKNOWN, check=True): """Convert a netmask to another notation.""" return _convert(nm, notation, inotation, _check=check, _isnm=True) # - Classes used to manage IP addresses, netmasks and the CIDR notation. class _IPv4Base(object): """Base class for IP addresses and netmasks.""" _isnm = False # Set to True when representing a netmask. def __init__(self, ip, notation=IP_UNKNOWN): """Initialize the object.""" self.set(ip, notation) def set(self, ip, notation=IP_UNKNOWN): """Set the IP address/netmask.""" self._ip_dec = long(_convert(ip, notation=IP_DEC, inotation=notation, _check=True, _isnm=self._isnm)) self._ip = _convert(self._ip_dec, notation=IP_DOT, inotation=IP_DEC, _check=False, _isnm=self._isnm) def get(self): """Return the address/netmask.""" return self.get_dot() def get_dot(self): """Return the dotted decimal notation of the address/netmask.""" return self._ip def get_hex(self): """Return the hexadecimal notation of the address/netmask.""" return _convert(self._ip_dec, notation=IP_HEX, inotation=IP_DEC, _check=False, _isnm=self._isnm) def get_bin(self): """Return the binary notation of the address/netmask.""" return _convert(self._ip_dec, notation=IP_BIN, inotation=IP_DEC, _check=False, _isnm=self._isnm) def get_dec(self): """Return the decimal notation of the address/netmask.""" return str(self._ip_dec) def get_oct(self): """Return the octal notation of the address/netmask.""" return _convert(self._ip_dec, notation=IP_OCT, inotation=IP_DEC, _check=False, _isnm=self._isnm) def __str__(self): """Print this address/netmask.""" return self.get() def _cmp_prepare(self, other): """Prepare the item to be compared with this address/netmask.""" if isinstance(other, self.__class__): return other._ip_dec elif isinstance(other, _IntegerTypes): # NOTE: this hides the fact that "other" can be a non valid IP/nm. return other return self.__class__(other)._ip_dec def __cmp__(self, other): """Compare two addresses/netmasks.""" cmp_val = 0 if self._ip_dec < self._cmp_prepare(other): cmp_val = -1 elif self._ip_dec > self._cmp_prepare(other): cmp_val = 1 if self._isnm: # NOTE: for netmasks invert values; compare netmasks by width. if cmp_val == -1: cmp_val = 1 elif cmp_val == 1: cmp_val = -1 return cmp_val def __int__(self): """Return the decimal representation of the address/netmask.""" return self._ip_dec def __long__(self): """Return the decimal representation of the address/netmask (long).""" return long(self._ip_dec) def __hex__(self): """Return the hexadecimal representation of the address/netmask.""" return self.get_hex() def __oct__(self): """Return the octal representation of the address/netmask.""" return self.get_oct() if not _isnm: ip = address = property(get, set, doc='The represented IP.') else: nm = netmask = property(get, set, doc='The represented netmask.') class IPv4Address(_IPv4Base): """An IPv4 Internet address. This class represents an IPv4 Internet address.""" def __repr__(self): """The representation string for this address.""" return '' % self.get() def _add(self, other): """Sum two IP addresses.""" if isinstance(other, self.__class__): sum = self._ip_dec + other._ip_dec elif isinstance(other, _IntegerTypes): sum = self._ip_dec + other else: other = self.__class__(other) sum = self._ip_dec + other._ip_dec return sum def __add__(self, other): """Sum two IP addresses.""" return IPv4Address(self._add(other), notation=IP_DEC) __radd__ = __add__ def __iadd__(self, other): """Augmented arithmetic sum.""" self.set(self._add(other), notation=IP_DEC) return self def _sub(self, other): """Subtract two IP addresses.""" if isinstance(other, self.__class__): sub = self._ip_dec - other._ip_dec if isinstance(other, _IntegerTypes): sub = self._ip_dec - other else: other = self.__class__(other) sub = self._ip_dec - other._ip_dec return sub def __sub__(self, other): """Subtract two IP addresses.""" return IPv4Address(self._sub(other), notation=IP_DEC) __rsub__ = __sub__ def __isub__(self, other): """Augmented arithmetic subtraction.""" self.set(self._sub(other), notation=IP_DEC) return self class IPv4NetMask(_IPv4Base): """An IPv4 Internet netmask. This class represents an IPv4 Internet netmask.""" _isnm = True def get_bits(self): """Return the bits notation of the netmask.""" return _convert(self._ip, notation=NM_BITS, inotation=IP_DOT, _check=False, _isnm=self._isnm) def get_wildcard(self): """Return the wildcard bits notation of the netmask.""" return _convert(self._ip, notation=NM_WILDCARD, inotation=IP_DOT, _check=False, _isnm=self._isnm) def __repr__(self): """The representation string for this netmask.""" return '' % self.get() class CIDR(object): """A CIDR address. The representation of a Classless Inter-Domain Routing (CIDR) address.""" def __init__(self, ip, netmask=None): self.set(ip, netmask) def set(self, ip, netmask=None): """Set the IP address and the netmask.""" if isinstance(ip, basestring) and netmask is None: ipnm = ip.split('/') if len(ipnm) != 2: raise ValueError, 'set: invalid CIDR: "%s"' % ip ip = ipnm[0] netmask = ipnm[1] if isinstance(ip, IPv4Address): self._ip = ip else: self._ip = IPv4Address(ip) if isinstance(netmask, IPv4NetMask): self._nm = netmask else: self._nm = IPv4NetMask(netmask) ipl = long(self._ip) nml = long(self._nm) base_add = ipl & nml self._ip_num = 0xFFFFFFFFL - 1 - nml # NOTE: quite a mess. # This's here to handle /32 (-1) and /31 (0) netmasks. if self._ip_num in (-1, 0): if self._ip_num == -1: self._ip_num = 1 else: self._ip_num = 2 self._net_ip = None self._bc_ip = None self._first_ip_dec = base_add self._first_ip = IPv4Address(self._first_ip_dec, notation=IP_DEC) if self._ip_num == 1: last_ip_dec = self._first_ip_dec else: last_ip_dec = self._first_ip_dec + 1 self._last_ip = IPv4Address(last_ip_dec, notation=IP_DEC) return None self._net_ip = IPv4Address(base_add, notation=IP_DEC) self._bc_ip = IPv4Address(base_add + self._ip_num + 1, notation=IP_DEC) self._first_ip_dec = base_add + 1 self._first_ip = IPv4Address(self._first_ip_dec, notation=IP_DEC) self._last_ip = IPv4Address(base_add + self._ip_num, notation=IP_DEC) def get(self): """Print this CIDR address.""" return '%s/%s' % (str(self._ip), str(self._nm)) def set_ip(self, ip): """Change the current IP.""" self.set(ip=ip, netmask=self._nm) def get_ip(self): """Return the given address.""" return self._ip def set_netmask(self, netmask): """Change the current netmask.""" self.set(ip=self._ip, netmask=netmask) def get_netmask(self): """Return the netmask.""" return self._nm def get_first_ip(self): """Return the first usable IP address.""" return self._first_ip def get_last_ip(self): """Return the last usable IP address.""" return self._last_ip def get_network_ip(self): """Return the network address.""" return self._net_ip def get_broadcast_ip(self): """Return the broadcast address.""" return self._bc_ip def get_ip_number(self): """Return the number of usable IP addresses.""" return self._ip_num def get_all_valid_ip(self): """Return a list of IPv4Address objects, one for every usable IP. WARNING: it's slow and can take a huge amount of memory for subnets with a large number of addresses. Use __iter__ instead ('for ip in ...').""" return list(self.__iter__()) def is_valid_ip(self, ip): """Return true if the given address in amongst the usable addresses, or if the given CIDR is contained in this one.""" if not isinstance(ip, (IPv4Address, CIDR)): if str(ip).find('/') == -1: ip = IPv4Address(ip) else: # Support for CIDR strings/objects, an idea of Nicola Novello. ip = CIDR(ip) if isinstance(ip, IPv4Address): if ip < self._first_ip or ip > self._last_ip: return False elif isinstance(ip, CIDR): # NOTE: manage /31 networks; 127.0.0.1/31 is considered to # be included in 127.0.0.1/8. if ip._nm._ip_dec == 0xFFFFFFFEL \ and self._nm._ip_dec != 0xFFFFFFFEL: compare_to_first = self._net_ip._ip_dec compare_to_last = self._bc_ip._ip_dec else: compare_to_first = self._first_ip._ip_dec compare_to_last = self._last_ip._ip_dec if ip._first_ip._ip_dec < compare_to_first or \ ip._last_ip._ip_dec > compare_to_last: return False return True def __str__(self): """Print this CIDR address.""" return self.get() def __repr__(self): """The representation string for this netmask.""" return '<%s/%s CIDR>' % (str(self.get_ip()), str(self.get_netmask())) def __len__(self): """Return the number of usable IP address.""" return self.get_ip_number() def __cmp__(self, other): """Compare two CIDR objects.""" if not isinstance(other, self.__class__): other = self.__class__(other) # NOTE: the only really interesting result is 0 to test equality; # in any other case: if this is a "wider" subnet, return 1; # if they are of the same width, sort by IPs. if self._nm < other._nm: return -1 elif self._nm > other._nm: return 1 if self._ip < other._ip: return -1 elif self._ip > other._ip: return 1 return 0 def __contains__(self, item): """Return true if the given address in amongst the usable addresses, or if the given CIDR is contained in this one.""" return self.is_valid_ip(item) def __iter__(self): """Iterate over IPv4Address objects, one for every usable IP.""" for i in xrange(0, self._ip_num): yield IPv4Address(self._first_ip_dec + i, notation=IP_DEC) cidr = property(get, set, doc='The represented CIDR.') ip = address = property(get_ip, set_ip, doc='The IP of this CIDR.') nm = netmask = property(get_netmask, set_netmask, doc='The netmask of this CIDR.') first_ip = property(get_first_ip) last_ip = property(get_last_ip) network_ip = property(get_network_ip) broadcast_ip = property(get_broadcast_ip) ip_number = property(get_ip_number) python-iplib_1.1.orig/setup.py0000755000000000000000000000314010760353567016703 0ustar00usergroup00000000000000#!/usr/bin/env python import sys from distutils.core import setup long_desc = """You can use this Python module to convert amongst many different notations and to manage couples of address/netmask in the CIDR notation. """ classifiers = """\ Development Status :: 4 - Beta Development Status :: 5 - Production/Stable Environment :: Console Environment :: No Input/Output (Daemon) Intended Audience :: Developers Intended Audience :: End Users/Desktop License :: OSI Approved :: GNU General Public License (GPL) Natural Language :: English Operating System :: OS Independent Programming Language :: Python Topic :: Software Development :: Libraries :: Python Modules Topic :: System :: Networking Topic :: Internet Topic :: Utilities """ params = {'name': 'iplib', 'version': '1.1', 'description': 'convert amongst many different IPv4 notations', 'long_description': long_desc, 'author': 'Davide Alberani', 'author_email': 'da@erlug.linux.it', 'maintainer': 'Davide Alberani', 'maintainer_email': 'da@erlug.linux.it', 'url': 'http://erlug.linux.it/~da/soft/iplib/', 'license': 'GPL', 'py_modules': ['iplib'], 'scripts': ['./bin/cidrinfo.py', './bin/ipconv.py', './bin/nmconv.py']} if sys.version_info >= (2, 1): params['keywords'] = ['ip', 'address', 'quad', 'dot', 'notation', 'binary', 'octal', 'hexadecimal', 'netmask', 'cidr', 'internet'] params['platforms'] = 'any' if sys.version_info >= (2, 3): params['download_url'] = 'http://erlug.linux.it/~da/soft/iplib/' params['classifiers'] = filter(None, classifiers.split("\n")) setup(**params) python-iplib_1.1.orig/test_iplib.py0000755000000000000000000002407510760353567017713 0ustar00usergroup00000000000000#!/usr/bin/env python import sys, random, unittest import iplib # Functions and values to test. # funct_name: (funct, [list of valid values], [list of invalid values]) FUNCTIONS = { 'is_dot': (iplib.is_dot, ['1.2.3.4', '0.0.0.0', '255.255.255.255'], ['1.2.3', '1.2.3.4.5', '-1.2.3.4', '256.0.0.0', '0.0.0.256' '10', '', 'a', '...', 'a.b.c.d', '1.2.3.']), 'is_hex': (iplib.is_hex, ['0', '0x0', '0x000000', '0xffffffff', '0', '123'], ['', '0x100000000L', '-1', '0xefg', '0x']), 'is_bin': (iplib.is_bin, ['00000000000000000000000000000000', '11111111111111111111111111111111', '01111111111111111111111111111111'], ['', '0000000000000000000000000000000', '1', '111111111111111111111111111111111', '00000000000000000000000000000002']), 'is_oct': (iplib.is_oct, ['0', '037777777777', '007777777777', '7777777', '7777777L'], ['', 'a', '040000000000', '040000000000L', '-1']), 'is_dec': (iplib.is_dec, ['0', '4294967295', '4294967295L', '294967295', '294967295L'], ['', 'a', '4294967296', '4294967296L', '-1']), 'is_dot_nm': (iplib.is_dot_nm, ['0.0.0.0', '255.255.255.255', '255.0.0.0', '255.255.255.0'], ['', '0.0.0.0.0', '255.255.256.255', '0.255.0.0', 'a', '...', '0.255.255.255']), 'is_hex_nm': (iplib.is_hex_nm, ['0x0', '0xFFFFFFFF', '0xFFFFFFFFL','0xFF000000', '0xFFFFFF00'], ['', '0xFF000001', '0xFEEEEEEE']), 'is_bin_nm': (iplib.is_bin_nm, ['00000000000000000000000000000000', '11111111111111111111111111111111', '11111111000000000000000000000000'], ['', '0', '0000000000000000000000000000000', '00000000000000000000000000000002']), 'is_oct_nm': (iplib.is_oct_nm, ['0', '00', '037777777777', '037700000000', '037777777400'], ['', '-1', '037777777775', '037700000001']), 'is_dec_nm': (iplib.is_dec_nm, ['0', '4294967040', '4294967295', '4294967040'], ['', 'a', '4294967039', '4294967293', '4294967296']), 'is_bits_nm': (iplib.is_bits_nm, [str(x) for x in xrange(0, 33)], ['', '-1', '33', 'a']), 'is_wildcard_nm': (iplib.is_wildcard_nm, ['255.255.255.255', '0.0.0.0', '0.255.255.255'], ['', '...', 'a.b.c.d', '0.0.0.0.0', '0.255.255.254', '255.0.255.255', '0.255.255.256']), } class MyTestResult(unittest.TestResult): def addFailure(self, test, err): errtxt = 'FAILURE (function %s): %s ' % \ (test.functName, test.currentValue) if test.shouldBevalid: errtxt += 'should NOT be VALID!' else: errtxt += 'should be VALID!' errtxt += '\n' sys.stderr.write(errtxt) unittest.TestResult.addFailure(self, test, err) mytestres = MyTestResult() class NotationsTest(unittest.TestCase): """Test functions used to check if an IP is in a given notation.""" currentValue = None shouldBevalid = None def defaultTestResult(self): return mytestres def runNotationsTest(): for key in FUNCTIONS: print 'TESTING %s... ' % key funct, valid, invalid = FUNCTIONS[key] def runTest(self): self.shouldBevalid = True self.functName = key for valid_val in valid: self.currentValue = valid_val self.failUnless(funct(valid_val)) self.shouldBevalid = False for invalid_val in invalid: self.currentValue = invalid_val self.failIf(funct(invalid_val)) setattr(NotationsTest, 'runTest', runTest) test = NotationsTest() test.run() class TestConvert(unittest.TestCase): """Test conversion amongst different notations.""" def test_ip(self): """Generate a number of random decimal IP; convert every IP in other notations and back, checking for differences.""" testDecIPs = ['0', '4294967295'] while len(testDecIPs) < 10000: randIP = str(random.randrange(4294967296L)) if randIP not in testDecIPs: testDecIPs.append(randIP) for ip in testDecIPs: for notation in ('hex', 'bin', 'oct', 'dec'): converted = iplib.convert(ip, notation=notation, inotation=iplib.IP_DEC, check=0) reverted = iplib.convert(converted, notation=iplib.IP_DEC, inotation=notation, check=0) self.failIf(ip != reverted) def test_nm(self): """convert every valid decimal NM in other notations and back, checking for differences.""" testBitNMs = [str(x) for x in iplib.VALID_NETMASKS.keys()] notations = [x[0] for x in iplib.NOTATION_MAP.values()] notations.remove('unknown') for nm in testBitNMs: for notation in notations: converted = iplib.convert_nm(nm, notation=notation, inotation=iplib.NM_BITS, check=0) reverted = iplib.convert_nm(converted, notation=iplib.NM_BITS, inotation=notation, check=0) self.failIf(nm != reverted) class TestIPv4Address(unittest.TestCase): def test_ip1(self): ip = iplib.IPv4Address('127.0.0.1') self.failIf(ip != '127.0.0.1') self.failIf(ip >= '127.0.0.2') self.failIf(ip <= '127.0.0.0') self.failUnless(ip == '127.0.0.1') self.failUnless(ip == iplib.IPv4Address('127.0.0.1')) def test_ip2(self): ip = iplib.IPv4Address('127.0.0.1') self.failUnless(ip.get_dot() == '127.0.0.1') self.failUnless(ip.get_hex() == '0x7F000001') self.failUnless(hex(ip) == '0x7F000001') self.failUnless(ip.get_bin() == '01111111000000000000000000000001') self.failUnless(ip.get_dec() == '2130706433') self.failUnless(int(ip) == 2130706433) self.failUnless(ip.get_oct() == '017700000001') self.failUnless(oct(ip) == '017700000001') def test_ip3(self): ip = iplib.IPv4Address('127.0.0.1') self.failUnless(ip + 0 == ip) self.failUnless(ip - 0 == ip) def test_ip4(self): ip1 = iplib.IPv4Address('127.0.0.1') ip2 = iplib.IPv4Address('127.0.0.1') self.failIf(ip1 is ip2) self.failIf(ip1 != ip2) self.failIf(ip1 is ip1 + 0) self.failIf(ip1 is ip1 - 0) self.failIf(ip1 + 1 != iplib.IPv4Address('127.0.0.2')) self.failIf(ip1 - 1 != iplib.IPv4Address('127.0.0.0')) self.failIf(1 + ip1 != iplib.IPv4Address('127.0.0.2')) self.failIf(1 - ip1 != iplib.IPv4Address('127.0.0.0')) _idip1 = id(ip1) ip1 += 0 self.failIf(id(ip1) != _idip1) ip1 += 1 self.failIf(id(ip1) != _idip1) ip1 -= 1 self.failIf(id(ip1) != _idip1) ip1 -= 0 self.failIf(id(ip1) != _idip1) class TestIPv4NetMask(unittest.TestCase): def test_nm1(self): nm = iplib.IPv4NetMask('255.0.0.0') self.failUnless(nm == '255.0.0.0') self.failUnless(nm == '037700000000') self.failUnless(nm == '4278190080') self.failUnless(nm == '8') def test_nm2(self): nm = iplib.IPv4NetMask('255.0.0.0') self.failUnless(nm.get_bits() == '8') self.failUnless(nm.get_wildcard() == '0.255.255.255') class TestCIDR(unittest.TestCase): def test_cidr1(self): cidr1 = iplib.CIDR('127.0.0.1/28') cidr2 = iplib.CIDR('127.0.0.1', '28') self.failIf(cidr1 != cidr2) def test_cidr2(self): cidr1 = iplib.CIDR('127.0.0.1/28') cidr2 = iplib.CIDR('0x7F000001', '037777777760') self.failIf(cidr1 != cidr2) def test_cidr3(self): cidr1 = iplib.CIDR('127.0.0.1/28') cidr2 = iplib.CIDR('127.0.0.1/8') self.failIf(cidr1 >= cidr2) def test_cidr4(self): cidr1 = iplib.CIDR('127.0.0.1/26') cidr2 = iplib.CIDR('127.0.0.2/26') self.failIf(cidr1 >= cidr2) def test_cidr5(self): cidr = iplib.CIDR('127.0.0.1/10') ip1 = iplib.IPv4Address('127.0.0.1') ip2 = iplib.IPv4Address('127.0.0.2') ip3 = iplib.IPv4Address('127.20.10.5') ip4 = iplib.IPv4Address('127.63.255.254') ipN = iplib.IPv4Address('127.0.0.0') ipB = iplib.IPv4Address('127.63.255.255') self.failUnless(ip1 in cidr) self.failUnless(ip2 in cidr) self.failUnless(ip3 in cidr) self.failUnless(ip4 in cidr) self.failIf(ipN in cidr) self.failIf(ipB in cidr) def test_cidr6(self): cidr = iplib.CIDR('127.0.0.1/31') ip1 = iplib.IPv4Address('127.0.0.0') ip2 = iplib.IPv4Address('127.0.0.1') self.failUnless(ip1 in cidr) self.failUnless(ip2 in cidr) self.failIf(iplib.IPv4Address('126.255.255.255') in cidr) self.failIf(iplib.IPv4Address('127.0.0.2') in cidr) def test_cidr7(self): cidr = iplib.CIDR('127.0.0.1/32') ip1 = iplib.IPv4Address('127.0.0.1') self.failUnless(ip1 in cidr) self.failIf(iplib.IPv4Address('127.0.0.0') in cidr) self.failIf(iplib.IPv4Address('127.0.0.2') in cidr) def test_cidr8(self): cidrBIG = iplib.CIDR('192.0.0.0/8') cidrSMALL = iplib.CIDR('192.0.0.0/30') cidrFUNNY = iplib.CIDR('192.0.0.0/31') self.failIf(cidrBIG in cidrSMALL) self.failUnless(cidrSMALL in cidrBIG) self.failUnless(cidrBIG in cidrBIG) self.failUnless(cidrSMALL in cidrSMALL) self.failIf(cidrSMALL in cidrFUNNY) self.failUnless(cidrFUNNY in cidrSMALL) def test_cidr_len(self): cidr = iplib.CIDR('127.0.0.1/28') self.failIf(len(cidr.get_all_valid_ip()) != 14) if __name__ == '__main__': runNotationsTest() print 'TESTING conversion... ' unittest.main()