一.socketserver模块
1.sockeserver的源码流程
2.简单的使用
socketserver服务端
import socketserver
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
msg = self.request.recv(1024)
print(msg)
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(("127.0.0.1",8888),MyServer) # 实例化对象
server.serve_forever()
socket客户端
import socket
client = socket.socket()
ip_port = ("127.0.0.1",8888)
client.connect(ip_port)
client.send(b"hello")
二.连接的合法性验证
1.os.urandom(n)加密
os.urandom(n)是一种bytes类型的随机生成n个字节字符串,而且每次生成的值都不相同,再加上md5等加密处理,就成了内容不同长度相同的字符串了
2.hmac
python自带的hmac模块实现了标准的Hmac算法
import hmac
message = b'Hello world' # 加密信息
key = b'secret' # 加密密匙
h = hmac.new(key,message,digestmod='MD5') # 密匙,信息,模式
print(h.hexdigest())
比较两个密文是否相同,可以用hmac.compare_digest(密文、密文),返回True或者False。
3.连接合法性验证服务端和客户端
服务端
import socket
import hmac , os
secret_key = b"This is key!"
# 只做验证 返回bool
def conn_auth(conn):
print("连接认证")
msg = os.urandom(32)
conn.send(msg)
h = hmac.new(secret_key,msg)
server_key = h.digest()
client_key = conn.recv(32)
# print(server_key,client_key)
return hmac.compare_digest(server_key,client_key)
# 判断验证
def data(conn):
if conn_auth(conn):
print("验证成功!")
conn.send("验证成功".encode("utf-8"))
while 1:
data = conn.recv(1024)
print(data)
else:
print("验证失败")
conn.send("验证失败".encode("utf-8"))
conn.close()
return
# 启动
def tcp_server(ip_port,):
server = socket.socket()
server.bind(ip_port)
server.listen()
while 1:
conn,addr = server.accept()
print(f"新连接: {addr[0]}:{addr[1]}")
data(conn)
if __name__ == '__main__':
ip_port = ("127.0.0.1",8888)
tcp_server(ip_port)
客户端
import socket
import os, hmac
# 密匙
sercet_key = b"This is key!"
# 使用密匙验证连接是否合法
def conn_auth(client):
msg = client.recv(32)
h = hmac.new(sercet_key, msg)
client_key = h.digest()
client.send(client_key)
# 验证判断
def tcp_client(ip_port):
client = socket.socket()
client.connect(ip_port)
conn_auth(client)
verify = client.recv(12).decode("utf-8")
while verify == "验证成功":
data = input("给服务端发送:").encode("utf-8")
client.send(data)
else:
print("连接被拒绝")
client.close()
if __name__ == '__main__':
ip_port = ("127.0.0.1", 8888)
tcp_client(ip_port)