python:验证客户端链接的合法性与socketserver

时间:2023-03-09 04:47:52
python:验证客户端链接的合法性与socketserver

一、验证客户端链接的合法性

 from socket import *
 import hmac,os

 secret_key=b'linhaifeng bang bang bang'
 def conn_auth(conn):
     '''
     认证客户端链接
     :param conn:
     :return:
     '''
     print('开始验证新链接的合法性')
     msg=os.urandom(32)
     conn.sendall(msg)
     h=hmac.new(secret_key,msg)
     digest=h.digest()
     respone=conn.recv(len(digest))
     return hmac.compare_digest(respone,digest)

 def data_handler(conn,bufsize=1024):
     if not conn_auth(conn):
         print('该链接不合法,关闭')
         conn.close()
         return
     print('链接合法,开始通信')
     while True:
         data=conn.recv(bufsize)
         if not data:break
         conn.sendall(data.upper())

 def server_handler(ip_port,bufsize,backlog=5):
     '''
     只处理链接
     :param ip_port:
     :return:
     '''
     tcp_socket_server=socket(AF_INET,SOCK_STREAM)
     tcp_socket_server.bind(ip_port)
     tcp_socket_server.listen(backlog)
     while True:
         conn,addr=tcp_socket_server.accept()
         print('新连接[%s:%s]' %(addr[0],addr[1]))
         data_handler(conn,bufsize)

 if __name__ == '__main__':
     ip_port=('127.0.0.1',9999)
     bufsize=1024
     server_handler(ip_port,bufsize)

服务端

 __author__ = 'Linhaifeng'
 from socket import *
 import hmac,os

 secret_key=b'linhaifeng bang bang bang'
 def conn_auth(conn):
     '''
     验证客户端到服务器的链接
     :param conn:
     :return:
     '''
     msg=conn.recv(32)
     h=hmac.new(secret_key,msg)
     digest=h.digest()
     conn.sendall(digest)

 def client_handler(ip_port,bufsize=1024):
     tcp_socket_client=socket(AF_INET,SOCK_STREAM)
     tcp_socket_client.connect(ip_port)

     conn_auth(tcp_socket_client)

     while True:
         data=input('>>: ').strip()
         if not data:continue
         if data == 'quit':break

         tcp_socket_client.sendall(data.encode('utf-8'))
         respone=tcp_socket_client.recv(bufsize)
         print(respone.decode('utf-8'))
     tcp_socket_client.close()

 if __name__ == '__main__':
     ip_port=('127.0.0.1',9999)
     bufsize=1024
     client_handler(ip_port,bufsize)

客户端

二、socketserver

import socketserver
class Myserver(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "127.0.0.1", 9999

    # 设置allow_reuse_address允许服务器重用地址
    socketserver.TCPServer.allow_reuse_address = True
    # 创建一个server, 将服务地址绑定到127.0.0.1:9999
    server = socketserver.TCPServer((HOST, PORT),Myserver)
    # 让server永远运行下去,除非强制停止程序
    server.serve_forever()

server端

import socket

HOST, PORT = "127.0.0.1", 9999
data = "hello"

# 创建一个socket链接,SOCK_STREAM代表使用TCP协议
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect((HOST, PORT))          # 链接到客户端
    sock.sendall(bytes(data + "\n", "utf-8")) # 向服务端发送数据
    received = str(sock.recv(1024), "utf-8")# 从服务端接收数据

print("Sent:     {}".format(data))
print("Received: {}".format(received))

client