udp数据包解析

新手上路,请多包涵

数据包长这个样子
clipboard.png

对应的proto格式

package fcs;

message FcsInfo
{
    message FreqKeyValue
    {
        optional string str_freq_id = 1;  //频控id
        optional uint32 uint32_expire_time = 2;
        optional uint32 uint32_value = 3; //频次返回值,请求的时候可以不带
        optional string str_soid = 4;
    }
    message FreqInfo
    {
        optional uint32 uint32_type   = 1; //0:qq or 1:appuser or 2:new appuser
        repeated FreqKeyValue rpt_freq_key_value = 2;
    }
    optional uint32 uint32_action = 1; //what to do (query, update or set), one of FCS_REQUEST_*
    repeated FreqInfo rpt_freq_info = 2;
    optional uint32 flag = 3; // flag to use qq/ip(0) or appuser(1) cookie as userID; 2 for both qq and appuser update
    optional string str_appuser = 4;  //appuser
    optional uint64 uin = 5; // qq number 
    optional string str_appid = 6;  //new appuser
    optional uint32 user_ip = 7; // user ip 
    optional uint32 err_code = 8; // return error code 
    optional string str_old_appid = 9;  //废除字段
    optional uint32 classification_id = 10;  //platform & product info
    optional string str_viewid = 11; //曝光id
}

解析代码:

    def getUDPData(self):
        print "read cap file :" + self.cappath
        f = open(self.cappath, 'rb')
        pcap = dpkt.pcap.Reader(f)
        postData = []
        starttime = int(time.time() * 1000)
        for ts, buf in pcap:
            try:
                eth = dpkt.ethernet.Ethernet(buf)
                ip = eth.data
                udp = ip.data
            except Exception, e:
                print Exception, ":", e
                continue
            # print tcp
            # print tcp.dport
            # Now see if we can parse the contents as a HTTP request
            try:
                print len(udp.data)
                req = FcsInfo() #for your server
                print "pcap data :"
                newdata = udp.data[24:]
                print len(newdata)
                print type(newdata)
                req.ParseFromString(newdata)
                print type(req), sys.getsizeof(req)
                print json_format.MessageToJson(req)
                break
                # print 'HTTP request: %s\n' % repr(request)
                # print request.method
                # print request.headers
                # print request.body
            except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError):
                print "error"
                continue
        endtime = int(time.time() * 1000)
        print "cost time is:" + str(endtime - starttime)
        return postData

输出结果:
clipboard.png

为啥是空的?

阅读 5.1k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏