wsaer 发表于 2017-5-2 10:57:16

python的socket发送C结构体

  公司因为测试需要,通过UDP发送C的一个结构体做测试。
这里用到的struct这个模块

结构体是这样的

typedef struct _vustr{
   DWORD dwStrHeader;
   DWORD dwDataLen;
   DWORD dwDevID;
   DWORD dwChnHLSD;
   int  nVUValue;
}VUSTR;



udp发送代码


#coding:gb2312

import socket
import os
import struct

dwStrHeader=33803
dwDataLen=12
dwDevID=452984837
dwChnHLSD=1
nVUValue=-80

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
data=struct.pack('IIIIi',dwStrHeader,dwDataLen,dwDevID,dwChnHLSD,nVUValue)
s.sendto(data,('192.168.0.199',33333))
s.close()


打包:struct.pack('格式化的字符串',变量1,变量2.....)
解包:struct.upack(data)

DWORD 是一个unsignedint字段。所以是 I


FormatC TypePythonNotesxpad byteno value ccharstring of length 1 bsignedcharinteger Bunsignedcharinteger ?_Boolbool(1)hshortinteger Hunsignedshortinteger iintinteger Iunsignedintinteger or long llonginteger Lunsignedlonglong qlonglonglong(2)Qunsignedlonglonglong(2)ffloatfloat ddoublefloat schar[]string pchar[]string Pvoid*long
页: [1]
查看完整版本: python的socket发送C结构体