utils.py
1 import socket 2 import os 3 import random 4 import string 5 6 from . import sam 7 8 def get_free_port(): 9 """Get a free port on your local host""" 10 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 12 s.bind(('', 0)) 13 free_port = s.getsockname()[1] 14 s.close() 15 return free_port 16 17 def is_address_accessible(address): 18 """Check if address is accessible or down""" 19 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 20 is_accessible = s.connect_ex(address) == 0 21 s.close() 22 return is_accessible 23 24 def address_from_string(address_string): 25 """Address tuple from host:port string""" 26 address = address_string.split(":") 27 return (address[0], int(address[1])) 28 29 def get_sam_address(): 30 """ 31 Get SAM address from environment variable I2P_SAM_ADDRESS, or use a default 32 value 33 """ 34 value = os.getenv("I2P_SAM_ADDRESS") 35 return address_from_string(value) if value else sam.DEFAULT_ADDRESS 36 37 def generate_session_id(length=6): 38 """Generate random session id""" 39 rand = random.SystemRandom() 40 sid = [rand.choice(string.ascii_letters) for _ in range(length)] 41 return "reticulum-" + "".join(sid) 42