socket认证客户端链接合法性
服务器端:
1 #_*_coding:utf-8_*_ 2 __author__ = 'Linhaifeng' 3 from socket import * 4 import hmac,os 5 6 secret_key=b'linhaifeng bang bang bang' 7 def conn_auth(conn): 8 ''' 9 认证客户端链接 10 :param conn: 11 :return: 12 ''' 13 print('开始验证新链接的合法性') 14 msg=os.urandom(32) 15 conn.sendall(msg) 16 h=hmac.new(secret_key,msg) 17 digest=h.digest() 18 respone=conn.recv(len(digest)) 19 return hmac.compare_digest(respone,digest) 20 21 def data_handler(conn,bufsize=1024): 22 if not conn_auth(conn): 23 print('该链接不合法,关闭') 24 conn.close() 25 return 26 print('链接合法,开始通信') 27 while True: 28 data=conn.recv(bufsize) 29 if not data:break 30 conn.sendall(data.upper()) 31 32 def server_handler(ip_port,bufsize,backlog=5): 33 ''' 34 只处理链接 35 :param ip_port: 36 :return: 37 ''' 38 tcp_socket_server=socket(AF_INET,SOCK_STREAM) 39 tcp_socket_server.bind(ip_port) 40 tcp_socket_server.listen(backlog) 41 while True: 42 conn,addr=tcp_socket_server.accept() 43 print('新连接[%s:%s]' %(addr[0],addr[1])) 44 data_handler(conn,bufsize) 45 46 if __name__ == '__main__': 47 ip_port=('127.0.0.1',9999) 48 bufsize=1024 49 server_handler(ip_port,bufsize)
客户端:
1 #_*_coding:utf-8_*_ 2 __author__ = 'Linhaifeng' 3 from socket import * 4 import hmac,os 5 6 secret_key=b'linhaifeng bang bang bang' 7 def conn_auth(conn): 8 ''' 9 验证客户端到服务器的链接 10 :param conn: 11 :return: 12 ''' 13 msg=conn.recv(32) 14 h=hmac.new(secret_key,msg) 15 digest=h.digest() 16 conn.sendall(digest) 17 18 def client_handler(ip_port,bufsize=1024): 19 tcp_socket_client=socket(AF_INET,SOCK_STREAM) 20 tcp_socket_client.connect(ip_port) 21 22 conn_auth(tcp_socket_client) 23 24 while True: 25 data=input('>>: ').strip() 26 if not data:continue 27 if data == 'quit':break 28 29 tcp_socket_client.sendall(data.encode('utf-8')) 30 respone=tcp_socket_client.recv(bufsize) 31 print(respone.decode('utf-8')) 32 tcp_socket_client.close() 33 34 if __name__ == '__main__': 35 ip_port=('127.0.0.1',9999) 36 bufsize=1024 37 client_handler(ip_port,bufsize)