- 纯标准库实现 Kademlia DHT(UDP + asyncio),报文 Ed25519 签名认证 - 超过 1200 字节的载荷自动分片与重组,上限 1 MiB - 公共聊天室:成员公告 + DHT 日志回放,迟到入群者也能补到历史 - 一对一私聊:X25519 + HKDF + AEAD 端到端加密,支持离线信箱 - Tkinter 图形界面,asyncio 运行在后台线程,事件经队列回传 UI - 局域网组播自动发现 + 手动引导地址(-b)两种互联方式 - run.cmd / start.bat 启动脚本,自动寻找 py -3 或 python - 48 个单元测试覆盖密码学原语、DHT 路由/协议与聊天层 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
57 lines
1.6 KiB
Python
57 lines
1.6 KiB
Python
"""Small shared helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import socket
|
|
import time
|
|
|
|
_CACHED_IP: tuple[float, str] | None = None
|
|
|
|
|
|
def local_ip() -> str:
|
|
"""Best guess of the LAN address of this machine (cached for 60s)."""
|
|
global _CACHED_IP
|
|
now = time.monotonic()
|
|
if _CACHED_IP and now - _CACHED_IP[0] < 60:
|
|
return _CACHED_IP[1]
|
|
address = "127.0.0.1"
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
try:
|
|
sock.connect(("8.8.8.8", 80))
|
|
address = sock.getsockname()[0]
|
|
except OSError:
|
|
try:
|
|
address = socket.gethostbyname(socket.gethostname())
|
|
except OSError:
|
|
address = "127.0.0.1"
|
|
finally:
|
|
sock.close()
|
|
_CACHED_IP = (now, address)
|
|
return address
|
|
|
|
|
|
def parse_host_port(text: str, default_port: int = 0) -> tuple[str, int]:
|
|
"""Parse ``host``, ``host:port`` or ``[v6]:port`` into a (host, port) pair."""
|
|
text = (text or "").strip()
|
|
if not text:
|
|
raise ValueError("empty address")
|
|
if text.startswith("["):
|
|
host, _, rest = text[1:].partition("]")
|
|
port = rest.lstrip(":")
|
|
return host, int(port) if port else default_port
|
|
if text.count(":") == 1:
|
|
host, _, port = text.partition(":")
|
|
return host, int(port) if port else default_port
|
|
if ":" in text:
|
|
return text, default_port
|
|
return text, default_port
|
|
|
|
|
|
def format_duration(seconds: float) -> str:
|
|
seconds = max(0, int(seconds))
|
|
if seconds < 60:
|
|
return f"{seconds}s"
|
|
if seconds < 3600:
|
|
return f"{seconds // 60}m{seconds % 60:02d}s"
|
|
return f"{seconds // 3600}h{(seconds % 3600) // 60:02d}m"
|