github.com/cnotch/ipchub@v1.1.0/utils/multicast.go (about) 1 // Copyright (c) 2019,CAOHONGJU All rights reserved. 2 // Use of this source code is governed by a MIT-style 3 // license that can be found in the LICENSE file. 4 5 package utils 6 7 import ( 8 "encoding/binary" 9 "net" 10 "sync" 11 ) 12 13 // MulticastIPS 全局组播池 14 var ( 15 Multicast = &multicast{ 16 ipseed: minIP, 17 portseed: minPort, 18 } 19 minIP = binary.BigEndian.Uint32([]byte{235, 0, 0, 0}) 20 maxIP = binary.BigEndian.Uint32([]byte{235, 255, 255, 255}) 21 minPort uint16 = 16666 22 maxPort uint16 = 39999 23 ) 24 25 // multicast 组播IP地址池 26 type multicast struct { 27 ipseed uint32 28 portseed uint16 29 l sync.Mutex 30 } 31 32 // NextIP 获取组播地址 33 func (p *multicast) NextIP() string { 34 p.l.Lock() 35 defer p.l.Unlock() 36 var ipbytes [4]byte 37 binary.BigEndian.PutUint32(ipbytes[:], p.ipseed) 38 ip := net.IP(ipbytes[:]).String() 39 p.ipseed++ 40 if p.ipseed > maxIP { 41 p.ipseed = minIP 42 } 43 return ip 44 } 45 46 func (p *multicast) NextPort() int { 47 p.l.Lock() 48 defer p.l.Unlock() 49 port := p.portseed 50 p.portseed++ 51 if p.portseed > maxPort { 52 p.portseed = minPort 53 } 54 return int(port) 55 }