美文网首页
python主机字节转网络序

python主机字节转网络序

作者: 你猜_19ca | 来源:发表于2018-09-04 14:08 被阅读0次

    百度简介

    网络传输一般采用大端序,也被称之为网络字节序,或网络序,即先发送高字节数据再发送低字节数据(如:四个字节由高位向低位用0-31标示后,将首先发送0-7位第一字节,在发送8-15第二字节,以此下去)。IP协议中定义大端为网络字节序

    伯克利socket API定义了一组转换函数,用于16和32bit整数在网络序和本机字节序之间的转换。htonl,htons用于本机序转换到网络序;ntohl,ntohs用于网络序转换到本机序。

    解决方案

    采用socket、struct
    socket: 用于转换网络序
    struct: 对python基本类型值与用python字符串格式表示的C struct类型间的转化

    • 发送 ( 本机 -> 网络序)
      1. 转换成网络序
      2. 打包成struct
      3. 发送打包后的字符串
      import struct
      import socket
      code = socket.htons(0xABCD)
      >> 48042
      str_code = struct.pack('H', code)
      >> b'\xaa\xbb'
      # 伪代码 
      客户端.send(str_code)
      
    • 接收 (网络序->本机)
      1. 接收网络序
      2. 解包struct
      3. 转换为本地字节
      # 伪代码
      data = 服务端.recv(buffersize)
      str_code = data[:2]
      >> b'\xaa\xbb'
      code = struct.unpack('=H', str_code)[0]
      >> 52651
      hex(socket.ntohs(code))
      >> '0xabcd'
      

    附赠struct打包格式表

    Format C Type Python type Standard size Notes
    x pad byte no value
    c char string of length 1 1
    b signed char integer 1 (3)
    B unsigned char integer 1 (3)
    ? _Bool bool 1 (1)
    h short integer 2 (3)
    H unsigned short integer 2 (3)
    i int integer 4 (3)
    I unsigned int integer 4 (3)
    l long integer 4 (3)
    L unsigned long integer 4 (3)
    q long long integer 8 (2), (3)
    Q unsigned long long integer 8 (2), (3)
    f float float 4 (4)
    d double float 8 (4)
    s char[] string
    p char[] string
    P void * integer (5), (3)

    相关文章

      网友评论

          本文标题:python主机字节转网络序

          本文链接:https://www.haomeiwen.com/subject/ygugwftx.html