服务端代码:
from socket import *
import hmac, os
secret_key = b'123456io p'
def conn_auth(conn):
'''
认证客户端链接
:param conn:
:return:
'''
print('开始验证新链接的合法性')
msg = os.urandom(32) #产生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:
:param bufsize:
:param backlog:
: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', 8000)
bufsize = 1024
server_handler(ip_port, bufsize)
合法客户端代码:
from socket import *
import hmac, os
secret_key = b'123456io p'
def conn_auth(conn):
'''
验证客户端到服务器的链接
:param conn:
:return:
'''
msg = conn.recv(32) #收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', 8000)
bufsize = 1024
client_handler(ip_port, bufsize)
from socket import *
def client_handler(ip_port, bufsize=1024):
tcp_socket_client = socket(AF_INET, SOCK_STREAM)
tcp_socket_client.connect(ip_port)
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', 8000)
bufsize = 1024
client_handler(ip_port, bufsize)