Skip to content

Instantly share code, notes, and snippets.

@koenbollen
Created November 28, 2010 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koenbollen/719226 to your computer and use it in GitHub Desktop.
Save koenbollen/719226 to your computer and use it in GitHub Desktop.
Utility to convert an address to a hash and back.
#!/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
print "usage: %s host port" % sys.argv[0]
print " or: %s hash" % sys.argv[0]
print
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