gopacket 中获取包源代码分析

我们使用gopacket 监听包的时候,常常采取下面2个例子获取包。

for packet := range packetSource.Packets() {
//    ...
//  }
        packets := packetSource.Packets()
        
        for {
                select {
                case packet := <-packets:
                        // A nil packet indicates the end of a pcap file.
                        if packet == nil {
                                return
                        }
                }
       }

这个包到底是怎么循环获取的?
我们找到源代码看看。。。

func (p *PacketSource) packetsToChannel() {
        defer close(p.c)
        for {
                packet, err := p.NextPacket()
                if err == io.EOF {
                        return
                } else if err == nil {
                        p.c <- packet
                }
        }
}

// Packets returns a channel of packets, allowing easy iterating over
// packets.  Packets will be asynchronously read in from the underlying
// PacketDataSource and written to the returned channel.  If the underlying
// PacketDataSource returns an io.EOF error, the channel will be closed.
// If any other error is encountered, it is ignored.
//
//  for packet := range packetSource.Packets() {
//    handlePacket(packet)  // Do something with each packet.
//  }
//
// If called more than once, returns the same channel.
func (p *PacketSource) Packets() chan Packet {
        if p.c == nil {
                p.c = make(chan Packet, 1000)
                go p.packetsToChannel()
        }
        return p.c
}

源代码中可以看出 ,采取了make(chan Packet,1000)
原来是采取了chan,
而 Packet是通过
p.NextPacket() 循环获取,再不停的输入到chan( <-)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,256评论 19 139
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 13,125评论 2 59
  • 1.笨,是一种保护色 跟我相处过的人,都会觉得我傻,因为他们觉得有便宜不占,是一个大傻瓜。 我一度的认为是不是我做...
    沐星之星星阅读 265评论 0 0
  • UI第一周 UIView及window UIKit是所有控件的所在库文件在AppDelegate.swift文件中...
    MissStitch丶阅读 278评论 0 3
  • 给各位相随离婚的人士看一看,相遇不易,结婚也不易,离婚更不易,不要轻易结婚也不要轻易离婚。 包小三的也要注意下怎么...
    笑傲江湖201710阅读 185评论 0 0