我们使用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( <-)
网友评论