Created
November 28, 2010 19:29
-
-
Save koenbollen/719226 to your computer and use it in GitHub Desktop.
Utility to convert an address to a hash and back.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Convert an address to a hash and back. | |
# | |
# Koen Bollen <meneer koenbollen nl> | |
# 2010 GPL | |
# | |
import socket | |
import struct | |
import base64 | |
__all__ = [ "addr2hash", "hash2addr" ] | |
def addr2hash( addr ): | |
"""Convert an address pair to a hash.""" | |
host, port = addr | |
try: | |
host = socket.gethostbyname( host ) | |
except (socket.gaierror, socket.error): | |
raise ValueError, "invalid host" | |
try: | |
port = int(port) | |
except ValueError: | |
raise ValueError, "invalid port" | |
bytes = socket.inet_aton( host ) | |
bytes += struct.pack( ">H", port ) | |
hash = base64.b64encode( bytes, "-_" ) | |
return hash | |
def hash2addr( hash ): | |
"""Convert a hash to an address pair.""" | |
try: | |
if len(hash) != 8: | |
raise TypeError | |
bytes = base64.b64decode( hash, "-_" ) | |
if len(bytes) != 6: | |
raise TypeError | |
except TypeError: | |
raise ValueError, "invalid hash" | |
assert len(bytes) == 6 | |
host = socket.inet_ntoa( bytes[:4] ) | |
port, = struct.unpack( ">H", bytes[-2:] ) | |
return host, port | |
def main(): | |
"""Sample and utility program.""" | |
import sys | |
if len(sys.argv) >= 3: | |
print addr2hash( (sys.argv[1], sys.argv[2]) ) | |
elif len(sys.argv) >= 2: | |
try: | |
host, port = hash2addr( sys.argv[1] ) | |
print host, port | |
except ValueError: | |
print >>sys.stderr, "error: invalid hash" | |
else: | |
print "Convert an address to a hash and back." | |
print "usage: %s host port" % sys.argv[0] | |
print " or: %s hash" % sys.argv[0] | |
print "Koen Bollen <meneer koenbollen nl>" | |
print "2010 GPL" | |
if __name__ == "__main__": | |
main() | |
# vim: expandtab shiftwidth=4 softtabstop=4 textwidth=79: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment