普通网友 2014-08-06 09:01
浏览 138
已采纳

在Go中使用元编程来解析网络协议

In JavaScript (Node), I've written a module which accepts a list of fields and their types and returns an object with pack and unpack methods. Below is the code to pack and unpack IPv4:

var ipv4 = proto.add('struct', {
  name: 'IPV4',
  fields: {
    version:       'int:4',
    ihl:           'int:4',
    dscp:          'int:6',
    ecn:           'int:2',
    length:        'int:16',
    id:            'int:16',
    flags:         'int:3',
    offset:        'int:13',
    ttl:           'int:8',
    protocol:      'int:8',
    checksum:      'int:16',
    src:           'IPV4_ADDR',
    dst:           'IPV4_ADDR',
    // TODO: IPv4 OPTIONS
    options:       'raw'
  },
  $length: 'length'
});
//then I can do
ipv4.pack({ version: 4, ... }); //=> buffer
//and
ipv4.unpack(buffer); //=> { ... }

Since JavaScript is dynamic, I can meta-program (reasonably) optimised pack and unpack functions. From what I understand, you cannot dynamically create functions in Go, though it appears this would be possible using the reflect package. Is this worth pursuing? Or would it be too costly to use reflect?

I'm hoping to avoid writing code like this for every network protocol I wish to parse.

  • 写回答

1条回答 默认 最新

  • dongyu6276 2014-08-06 10:45
    关注

    If can accept a semi-dynamic solution, you could take inspiration in the numerous JSON alternative packages for Golang that are designed for speed. Their approach is to tag a struct, then run a tool (as part of a make configuration for example) to generate the MarshalJSON and UnmarshalJSON methods for the desired types. Which is clearly faster than using tags.

    Some examples to help you :

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏