100 lines
3.2 KiB
Python
100 lines
3.2 KiB
Python
import sys
|
|
import ipaddress
|
|
import os
|
|
from cli.app import P2PChatApp
|
|
|
|
# 获取当前目录
|
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
# 朋友的公钥路径
|
|
friend_public_key_path = os.path.join(BASE_DIR,"ipchat", 'config', 'keys', 'send', 'public.key')
|
|
|
|
# 你自己的私钥和公钥路径
|
|
my_private_key_path = os.path.join(BASE_DIR,"ipchat", 'config', 'keys', 'user', 'private.pem')
|
|
my_public_key_path = os.path.join(BASE_DIR,"ipchat", 'config', 'keys', 'user', 'public.pem')
|
|
|
|
|
|
def is_valid_ip(ip: str) -> bool:
|
|
try:
|
|
ipaddress.ip_address(ip)
|
|
return True
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def is_valid_port(port_str: str) -> bool:
|
|
if not port_str.isdigit():
|
|
return False
|
|
port = int(port_str)
|
|
return 1 <= port <= 65535
|
|
|
|
|
|
def main():
|
|
print("欢迎使用P2P加密聊天系统")
|
|
print("输入 'q' 或 'exit' 退出程序")
|
|
|
|
# 创建P2PChatApp实例,传入公私钥路径
|
|
app = P2PChatApp(friend_public_key_path, my_private_key_path, my_public_key_path)
|
|
|
|
while True:
|
|
print("\n请选择模式:")
|
|
print("1. 发送消息(持续模式)")
|
|
print("2. 监听消息")
|
|
print("0. 退出")
|
|
|
|
choice = input("输入选项(0/1/2): ").strip().lower()
|
|
if choice in ("0", "q", "exit"):
|
|
print("再见!退出程序")
|
|
break
|
|
|
|
elif choice == "1":
|
|
# 获取目标IP和端口
|
|
while True:
|
|
target_ip = input("请输入目标IP地址: ").strip()
|
|
if target_ip.lower() in ("q", "exit"):
|
|
break
|
|
if not is_valid_ip(target_ip):
|
|
print("❌ IP格式错误,请重新输入")
|
|
continue
|
|
|
|
while True:
|
|
target_port = input("请输入目标端口(1-65535): ").strip()
|
|
if target_port.lower() in ("q", "exit"):
|
|
break
|
|
if not is_valid_port(target_port):
|
|
print("❌ 端口无效,请输入1-65535的数字")
|
|
continue
|
|
break
|
|
|
|
if target_port.lower() in ("q", "exit"):
|
|
continue
|
|
|
|
# 进入持续发送模式
|
|
app.send_mode(target_ip, int(target_port))
|
|
break # 发送循环结束后回到主菜单
|
|
|
|
elif choice == "2":
|
|
while True:
|
|
listen_port = input("请输入监听端口(1-65535): ").strip()
|
|
if listen_port.lower() in ("q", "exit"):
|
|
break
|
|
if not is_valid_port(listen_port):
|
|
print("❌ 端口无效,请输入1-65535的数字")
|
|
continue
|
|
break
|
|
|
|
if listen_port.lower() in ("q", "exit"):
|
|
continue
|
|
|
|
print("开始监听,按 Ctrl+C 停止")
|
|
try:
|
|
app.listen_mode(int(listen_port))
|
|
except KeyboardInterrupt:
|
|
print("\n监听已停止")
|
|
|
|
else:
|
|
print("❌ 无效选项,请重新输入")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |