Python论坛  - 讨论区

标题:Python Cookbook 之 Naming Slice

2014年03月13日 星期四 09:51

在很多应用层的网络传输协议中,为了提高效率,会把很多个数据元素以二进制的方式拼凑在一起,比如socks的协议:

Client to SOCKS server:

  • field 1: SOCKS version number, 1 byte, must be 0x04 for this version
  • field 2: command code, 1 byte:
    • 0x01 = establish a TCP/IP stream connection
    • 0x02 = establish a TCP/IP port binding
  • field 3: network byte order port number, 2 bytes
  • field 4: deliberate invalid IP address, 4 bytes, first three must be 0x00 and the last one must not be 0x00
  • field 5: the user ID string, variable length, terminated with a null (0x00)
  • field 6: the domain name of the host we want to contact, variable length, terminated with a null (0x00)

Server to SOCKS client:

  • field 1: null byte
  • field 2: status, 1 byte:
    • 0x5a = request granted
    • 0x5b = request rejected or failed
    • 0x5c = request failed because client is not running identd (or not reachable from the server)
    • 0x5d = request failed because client's identd could not confirm the user ID string in the request
  • field 3: network byte order port number, 2 bytes
  • field 4: network byte order IP address, 4 bytes

要解析这样的数据,我们可以使用Python的Slice方法,例如:

data[x:y]表示端口号,data[m:n]表示IP地址,等等。

为了使程序更加清晰易懂,我们可以将上述Slice定义为Naming Slice,使之意义更加明确(而不是一堆Magic Number),这样可以大大方便程序的阅读者理解数据段的含义。

Naming Slice的使用方法示例如下:

items=[0,1,2,3,4,5,6,7,8,9]
x=slice(2,4)
print(items[x])
items[x]=[1,2,3]
print(items)
del items[x]
print(items)
print(items[x])

参考资料:

http://docs.python.org/3/library/functions.html#slice

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号