天天看点

Python从门到精通(七):网络-06-客户端相关

一、客户端认证

1.1、认证

import hmac
import os

def client_authenticate(connection, secret_key):
    """
    Authenticate client to a remote service.
    connection represents a network connection.
    secret_key is a key known only to both client/server.
    :param connection:
    :param secret_key:
    :return:
    """
    message = connection.recv(32)
    hash = hmac.new(secret_key, message)
    digest = hash.digest()
    connection.send(digest)

def server_authenticate(connection, secret_key):
    """
    Request client authentication.
    :param connection:
    :param secret_key:
    :return:
    """
    message = os.urandom(32)
    connection.send(message)
    hash = hmac.new(secret_key, message)
    digest = hash.digest()
    response = connection.recv(len(digest))
    return hmac.compare_digest(digest,response)      

1.2、集成

from socket import socket, AF_INET, SOCK_STREAM
from chapter11.client_auth import server_authenticate

secret_key = b'peekaboo'
def echo_handler(client_sock):
    if not server_authenticate(client_sock, secret_key):
        client_sock.close()
        return
    while True:

        # msg = client_sock.recv(8192)
        if not (msg := client_sock.recv(8192)):
            break
        client_sock.sendall(msg)

def echo_server(address):
    s = socket(AF_INET, SOCK_STREAM)
    s.bind(address)
    s.listen(5)
    while True:
        c,a = s.accept()
        echo_handler(c)

echo_server(('', 18000))      

二、工具类

2.1、IP地址处理

import ipaddress

net = ipaddress.ip_network('193.145.37.64/30')
print(f'net is: {net}')

for n in net:
    print(f'ip address is: {n}')

net_6 = ipaddress.ip_network('12:3456:78:90ab:cd:ef01:23:30/127')
print(f'ip net 6 is: {net_6}')
for n in net_6:
    print(f'net 6 address: {n}')


print(f'num addresses: {net.num_addresses}')
print(f'num 0: {net[0]}')
print(f'num 1: {net[1]}')


a = ipaddress.ip_address('193.145.37.67')
print(f'{a} in net is: {a in net}')
b = ipaddress.ip_address('193.145.37.97')
print(f'{b} in net is: {b in net}')


i_net = ipaddress.ip_interface('193.145.37.67/27')
print(f'network: {i_net.network}')
print(f'ip is: {i_net.ip}')


local_host = ipaddress.ip_address('127.0.0.1')
from socket import socket, AF_INET, SOCK_STREAM
s = socket(AF_INET, SOCK_STREAM)
s.connect((a, 8080))
s.connect((str(a), 8080))      

2.2、服务间信息共享

from multiprocessing.connection import Listener
import traceback

def echo_client(conn):
    try:
        while True:
            msg = conn.recv()
            conn.send(msg)
    except EOFError:
        print('Connection closed')

def echo_server(address, authkey):
    serv = Listener(address, authkey=authkey)
    while True:
        try:
            client = serv.accept()

            echo_client(client)
        except Exception:
            traceback.print_exc()

echo_server(('', 25000), authkey=b'peekaboo')      

2.3、大文件处理

def send_from(arr, dest):
    view = memoryview(arr).cast('B')
    while len(view):
        nsent = dest.send(view)
        view = view[nsent:]

def recv_into(arr, source):
    view = memoryview(arr).cast('B')
    while len(view):
        nrecv = source.recv_into(view)
        view = view[nrecv:]      
import numpy
from socket import *
from chapter11.big_data import send_from, recv_into

a = numpy.arange(0.0, 50000000.0)
c = socket(AF_INET, SOCK_STREAM)
send_from(a, c)

# Client
import numpy
a = numpy.zeros(shape=50000000, dtype=float)
print(a[0:10])
recv_into(a, c)
c = socket(AF_INET, SOCK_STREAM)
print(a[0:10])      
from socket import *
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', 25000))
s.listen(1)
c,a = s.accept()

from socket import *
c = socket(AF_INET, SOCK_STREAM)
c.connect(('localhost', 25000))