本文整理汇总了Golang中net.ListenPacket函数的典型用法代码示例。如果您正苦于以下问题:Golang ListenPacket函数的具体用法?Golang ListenPacket怎么用?Golang ListenPacket使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ListenPacket函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestUDPMultiplePacketConnWithMultipleGroupListeners
func TestUDPMultiplePacketConnWithMultipleGroupListeners(t *testing.T) {
switch runtime.GOOS {
case "nacl", "plan9", "windows":
t.Skipf("not supported on %s", runtime.GOOS)
}
if testing.Short() {
t.Skip("to avoid external network")
}
for _, gaddr := range udpMultipleGroupListenerTests {
c1, err := net.ListenPacket("udp4", "224.0.0.0:1024") // wildcard address with reusable port
if err != nil {
t.Fatal(err)
}
defer c1.Close()
c2, err := net.ListenPacket("udp4", "224.0.0.0:1024") // wildcard address with reusable port
if err != nil {
t.Fatal(err)
}
defer c2.Close()
var ps [2]*ipv4.PacketConn
ps[0] = ipv4.NewPacketConn(c1)
ps[1] = ipv4.NewPacketConn(c2)
var mift []*net.Interface
ift, err := net.Interfaces()
if err != nil {
t.Fatal(err)
}
for i, ifi := range ift {
if _, ok := nettest.IsMulticastCapable("ip4", &ifi); !ok {
continue
}
for _, p := range ps {
if err := p.JoinGroup(&ifi, gaddr); err != nil {
t.Fatal(err)
}
}
mift = append(mift, &ift[i])
}
for _, ifi := range mift {
for _, p := range ps {
if err := p.LeaveGroup(ifi, gaddr); err != nil {
t.Fatal(err)
}
}
}
}
}
示例2: TestUDPMultiplePacketConnWithMultipleGroupListeners
func TestUDPMultiplePacketConnWithMultipleGroupListeners(t *testing.T) {
switch runtime.GOOS {
case "dragonfly", "plan9", "solaris", "windows":
t.Skipf("not supported on %q", runtime.GOOS)
}
if !supportsIPv6 {
t.Skip("ipv6 is not supported")
}
for _, gaddr := range udpMultipleGroupListenerTests {
c1, err := net.ListenPacket("udp6", "[ff02::]:1024") // wildcard address with reusable port
if err != nil {
t.Fatalf("net.ListenPacket failed: %v", err)
}
defer c1.Close()
c2, err := net.ListenPacket("udp6", "[ff02::]:1024") // wildcard address with reusable port
if err != nil {
t.Fatalf("net.ListenPacket failed: %v", err)
}
defer c2.Close()
var ps [2]*ipv6.PacketConn
ps[0] = ipv6.NewPacketConn(c1)
ps[1] = ipv6.NewPacketConn(c2)
var mift []*net.Interface
ift, err := net.Interfaces()
if err != nil {
t.Fatalf("net.Interfaces failed: %v", err)
}
for i, ifi := range ift {
if _, ok := isMulticastAvailable(&ifi); !ok {
continue
}
for _, p := range ps {
if err := p.JoinGroup(&ifi, gaddr); err != nil {
t.Fatalf("ipv6.PacketConn.JoinGroup %v on %v failed: %v", gaddr, ifi, err)
}
}
mift = append(mift, &ift[i])
}
for _, ifi := range mift {
for _, p := range ps {
if err := p.LeaveGroup(ifi, gaddr); err != nil {
t.Fatalf("ipv6.PacketConn.LeaveGroup %v on %v failed: %v", gaddr, ifi, err)
}
}
}
}
}
示例3: TestUDPMultipleConnWithMultipleGroupListeners
func TestUDPMultipleConnWithMultipleGroupListeners(t *testing.T) {
if testing.Short() || !*testExternal {
t.Logf("skipping test to avoid external network")
return
}
for _, tt := range udpMultipleGroupListenerTests {
// listen to a group address, actually a wildcard address
// with reusable port
c1, err := net.ListenPacket("udp4", "224.0.0.0:1024") // see RFC 4727
if err != nil {
t.Fatalf("net.ListenPacket failed: %v", err)
}
defer c1.Close()
c2, err := net.ListenPacket("udp4", "224.0.0.0:1024") // see RFC 4727
if err != nil {
t.Fatalf("net.ListenPacket failed: %v", err)
}
defer c2.Close()
var ps [2]*ipv4.PacketConn
ps[0] = ipv4.NewPacketConn(c1)
ps[1] = ipv4.NewPacketConn(c2)
var mift []*net.Interface
ift, err := net.Interfaces()
if err != nil {
t.Fatalf("net.Interfaces failed: %v", err)
}
for i, ifi := range ift {
if _, ok := isGoodForMulticast(&ifi); !ok {
continue
}
for _, p := range ps {
if err := p.JoinGroup(&ifi, tt.gaddr); err != nil {
t.Fatalf("ipv4.PacketConn.JoinGroup %v on %v failed: %v", tt.gaddr, ifi, err)
}
}
mift = append(mift, &ift[i])
}
for _, ifi := range mift {
for _, p := range ps {
if err := p.LeaveGroup(ifi, tt.gaddr); err != nil {
t.Fatalf("ipv4.PacketConn.LeaveGroup %v on %v failed: %v", tt.gaddr, ifi, err)
}
}
}
}
}
示例4: NewSocket
// addr is used to create a listening UDP conn which becomes the underlying
// net.PacketConn for the Socket.
func NewSocket(network, addr string) (s *Socket, err error) {
pc, err := net.ListenPacket(network, addr)
if err != nil {
return
}
return NewSocketFromPacketConn(pc)
}
示例5: mustListenPacket
func mustListenPacket(addr string) net.PacketConn {
c, err := net.ListenPacket("udp", addr)
if err != nil {
panic(err)
}
return c
}
示例6: Start
func (s *serfDiscovery) Start() error {
conn, err := net.ListenPacket("udp4", "0.0.0.0:1024")
if err != nil {
return err
}
s.pconn = ipv4.NewPacketConn(conn)
if err := s.pconn.JoinGroup(s.iface, &net.UDPAddr{IP: s.group}); err != nil {
conn.Close()
return err
}
if err := s.pconn.SetControlMessage(ipv4.FlagDst, true); err != nil {
conn.Close()
return err
}
go func() {
<-s.stop
conn.Close()
}()
go func() {
b := make([]byte, 1500)
for {
_, cm, src, err := s.pconn.ReadFrom(b)
if err != nil {
if strings.Contains(err.Error(), "closed network connection") {
log.Printf("Closed connection, stopping discovery listener...")
return
}
log.Printf("Failed to read packet: %s", err)
continue
}
if cm.Dst.IsMulticast() {
if cm.Dst.Equal(s.group) {
sip, _, err := net.SplitHostPort(src.String())
if err != nil {
log.Printf("Multicast src '%s' has unexpected format: %s", src, err)
}
if sip == s.self.String() {
continue
}
err = s.serf.Join(sip)
if err != nil {
log.Printf("Failed to join serf gossip at '%s': %s ", sip, err)
}
} else {
continue
}
}
}
}()
return nil
}
示例7: TestAnnounceLocalhost
func TestAnnounceLocalhost(t *testing.T) {
t.Parallel()
srv := server{
t: map[[20]byte]torrent{
[20]byte{0xa3, 0x56, 0x41, 0x43, 0x74, 0x23, 0xe6, 0x26, 0xd9, 0x38, 0x25, 0x4a, 0x6b, 0x80, 0x49, 0x10, 0xa6, 0x67, 0xa, 0xc1}: {
Seeders: 1,
Leechers: 2,
Peers: []util.CompactPeer{
{[]byte{1, 2, 3, 4}, 5},
{[]byte{6, 7, 8, 9}, 10},
},
},
},
}
var err error
srv.pc, err = net.ListenPacket("udp", ":0")
require.NoError(t, err)
defer srv.pc.Close()
go func() {
require.NoError(t, srv.serveOne())
}()
req := AnnounceRequest{
NumWant: -1,
Event: Started,
}
rand.Read(req.PeerId[:])
copy(req.InfoHash[:], []uint8{0xa3, 0x56, 0x41, 0x43, 0x74, 0x23, 0xe6, 0x26, 0xd9, 0x38, 0x25, 0x4a, 0x6b, 0x80, 0x49, 0x10, 0xa6, 0x67, 0xa, 0xc1})
go func() {
require.NoError(t, srv.serveOne())
}()
ar, err := Announce(fmt.Sprintf("udp://%s/announce", srv.pc.LocalAddr().String()), &req)
require.NoError(t, err)
assert.EqualValues(t, 1, ar.Seeders)
assert.EqualValues(t, 2, len(ar.Peers))
}
示例8: NewUDPHook
// NewUDPHook returns logrus-compatible hook that sends data to UDP socket
func NewUDPHook(opts ...UDPOptionSetter) (*UDPHook, error) {
f := &UDPHook{}
for _, o := range opts {
o(f)
}
if f.Clock == nil {
f.Clock = clockwork.NewRealClock()
}
if f.clientNet == "" {
f.clientNet = UDPDefaultNet
}
if f.clientAddr == "" {
f.clientAddr = UDPDefaultAddr
}
addr, err := net.ResolveUDPAddr(f.clientNet, f.clientAddr)
if err != nil {
return nil, Wrap(err)
}
conn, err := net.ListenPacket("udp", ":0")
if err != nil {
return nil, Wrap(err)
}
f.addr = addr
f.conn = conn.(*net.UDPConn)
return f, nil
}
示例9: Start
func (nr *NetworkReader) Start() {
connection, err := net.ListenPacket("udp4", nr.host)
if err != nil {
nr.logger.Fatalf("Failed to listen on port. %s", err)
}
nr.logger.Infof("Listening on port %s", nr.host)
nr.lock.Lock()
nr.connection = connection
nr.lock.Unlock()
readBuffer := make([]byte, 65535) //buffer with size = max theoretical UDP size
for {
readCount, senderAddr, err := connection.ReadFrom(readBuffer)
if err != nil {
nr.logger.Debugf("Error while reading. %s", err)
return
}
nr.logger.Debugf("NetworkReader: Read %d bytes from address %s", readCount, senderAddr)
readData := make([]byte, readCount) //pass on buffer in size only of read data
copy(readData, readBuffer[:readCount])
atomic.AddUint64(&nr.receivedMessageCount, 1)
atomic.AddUint64(&nr.receivedByteCount, uint64(readCount))
metrics.BatchIncrementCounter(nr.contextName + ".receivedMessageCount")
metrics.BatchAddCounter(nr.contextName+".receivedByteCount", uint64(readCount))
nr.writer.Write(readData)
}
}
示例10: TestPacketConnMulticastSocketOptions
func TestPacketConnMulticastSocketOptions(t *testing.T) {
switch runtime.GOOS {
case "nacl", "plan9", "solaris", "windows":
t.Skipf("not supported on %s", runtime.GOOS)
}
if !supportsIPv6 {
t.Skip("ipv6 is not supported")
}
ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagMulticast|net.FlagLoopback)
if ifi == nil {
t.Skipf("not available on %s", runtime.GOOS)
}
m, ok := nettest.SupportsRawIPSocket()
for _, tt := range packetConnMulticastSocketOptionTests {
if tt.net == "ip6" && !ok {
t.Log(m)
continue
}
c, err := net.ListenPacket(tt.net+tt.proto, tt.addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
p := ipv6.NewPacketConn(c)
defer p.Close()
if tt.src == nil {
testMulticastSocketOptions(t, p, ifi, tt.grp)
} else {
testSourceSpecificMulticastSocketOptions(t, p, ifi, tt.grp, tt.src)
}
}
}
示例11: icmpListen
func icmpListen(v6 bool, ch chan ICMPMessage) {
afnet := "ip4:icmp"
if v6 {
afnet = "ip6:ipv6-icmp"
}
c, err := net.ListenPacket(afnet, "")
if err != nil {
debug.Printf("ListenPacket failed: %v", err)
return
}
defer c.Close()
rawICMP := make([]byte, 256)
for {
_, fromAddr, err := c.ReadFrom(rawICMP)
if err != nil {
debug.Printf("ReadFrom failed: %v", err)
return
}
msg, err := parseICMP(v6, fromAddr, rawICMP)
if err != nil {
debug.Printf("parseICMP failed: %v", err)
continue
}
ch <- msg
}
}
示例12: newLocalPacketListener
func newLocalPacketListener(network string) (net.PacketConn, error) {
switch network {
case "udp":
if c, err := net.ListenPacket("udp4", "127.0.0.1:0"); err == nil {
return c, nil
}
return net.ListenPacket("udp6", "[::1]:0")
case "udp4":
return net.ListenPacket("udp4", "127.0.0.1:0")
case "udp6":
return net.ListenPacket("udp6", "[::1]:0")
case "unixgram":
return net.ListenPacket(network, localPath())
}
return nil, fmt.Errorf("%s is not supported", network)
}
示例13: main
func main() {
flag.Parse()
ip, n, err := net.ParseCIDR(*src)
if err != nil {
log.Fatal(err)
}
c, err := net.ListenPacket("udp", net.JoinHostPort("0.0.0.0", fmt.Sprintf("%d", *port)))
if err != nil {
log.Fatal(err)
}
defer c.Close()
go func() {
dst := broadcast(n)
for {
if err := advert(c, ip, dst, n); err != nil {
log.Println(err)
}
time.Sleep(5 * time.Second)
}
}()
b := make([]byte, 8192)
for {
n, peer, err := c.ReadFrom(b)
if err != nil {
log.Println(err)
continue
}
log.Printf("%d bytes rcvd from %v, %q\n", n, peer, string(b[:n]))
}
}
示例14: newUDPEchoServer
func newUDPEchoServer() (*udpEchoServer, error) {
packetconn, err := net.ListenPacket("udp", ":0")
if err != nil {
return nil, err
}
return &udpEchoServer{packetconn}, nil
}
示例15: main
func main() {
listen = flag.String("listen", "127.0.0.1:4443", "Listen on this address.")
quite = flag.Bool("quite", false, "Quite mode.")
statsonly = flag.Bool(
"statsonly", false, "Only prints stats on stdout and discard data.",
)
flag.Parse()
conn, err := net.ListenPacket("udp4", *listen)
if err != nil {
fmt.Println(err)
return
}
if !*quite {
if *statsonly {
fmt.Printf(
"UDP: Server started on %s in statsonly mode.\n", *listen,
)
} else {
fmt.Printf("UDP: Server started on %s.\n", *listen)
}
}
obytes := make([]byte, 64*1024)
start := time.Now()
var bcount, count time.Duration
for {
bytes := obytes
n, _, err := conn.ReadFrom(bytes)
if err != nil {
fmt.Println(err)
continue
}
if *statsonly {
count += 1
bcount += time.Duration(n)
now := time.Now()
diff := now.Sub(start)
if diff > 1e9 {
fmt.Printf(
"bps = %sps, pps = %d.\n",
gutils.FormatBytes(float64(bcount)), count,
)
start = now
bcount, count = 0, 0
}
} else {
bytes = bytes[:n]
fmt.Printf(string(bytes))
}
}
}