1 Star 0 Fork 0

kennyzhu2015 / go-sip-ua

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
util.go 2.12 KB
一键复制 编辑 原始数据 按行查看 历史
zhuwei6 提交于 2022-12-09 11:51 . init
package utils
import (
"errors"
"fmt"
"math/rand"
"net"
"strconv"
"strings"
"gitee.com/kennyzw/gosip/sip"
)
var (
localIPPrefix = [...]string{"192.168", "10.0", "169.254", "172.16"}
ErrPort = errors.New("invalid port")
)
// branch 是从via头域获取.
// 参考:https://www.jianshu.com/p/84d7289a4d3b.
func GetBranchID(msg sip.Message) sip.MaybeString {
if viaHop, ok := msg.ViaHop(); ok {
if branch, ok := viaHop.Params.Get("branch"); ok {
return branch
}
}
return nil
}
func GetIP(addr string) string {
if strings.Contains(addr, ":") {
return strings.Split(addr, ":")[0]
}
return ""
}
func GetPort(addr string) string {
if strings.Contains(addr, ":") {
return strings.Split(addr, ":")[1]
}
return ""
}
func StrToUint16(str string) uint16 {
i, _ := strconv.ParseUint(str, 10, 16)
return uint16(i)
}
func BuildContactHeader(name string, from, to sip.Message, expires *sip.Expires) {
name = strings.ToLower(name)
for _, h := range from.GetHeaders(name) {
AddParamsToContact(h.(*sip.ContactHeader), expires)
to.AppendHeader(h.Clone())
}
}
func AddParamsToContact(contact *sip.ContactHeader, expires *sip.Expires) {
if urn, ok := contact.Params.Get("+sip.instance"); ok {
contact.Params.Add("+sip.instance", sip.String{Str: fmt.Sprintf(`"%s"`, urn)})
}
if expires != nil {
contact.Params.Add("expires", sip.String{Str: fmt.Sprintf("%d", int(*expires))})
}
}
func ListenUDPInPortRange(portMin, portMax int, laddr *net.UDPAddr) (*net.UDPConn, error) {
if (laddr.Port != 0) || ((portMin == 0) && (portMax == 0)) {
return net.ListenUDP("udp", laddr)
}
var i, j int
i = portMin
if i == 0 {
i = 1
}
j = portMax
if j == 0 {
j = 0xFFFF
}
if i > j {
return nil, ErrPort
}
portStart := rand.Intn(j-i+1) + i
portCurrent := portStart
for {
*laddr = net.UDPAddr{IP: laddr.IP, Port: portCurrent}
c, e := net.ListenUDP("udp", laddr)
if e == nil {
return c, e
}
portCurrent++
if portCurrent > j {
portCurrent = i
}
fmt.Printf("failed to listen %s: %v, try next port %d", laddr.String(), e, portCurrent)
if portCurrent == portStart {
break
}
}
return nil, ErrPort
}
Go
1
https://gitee.com/kennyzw/go-sip-ua.git
git@gitee.com:kennyzw/go-sip-ua.git
kennyzw
go-sip-ua
go-sip-ua
1df5730d3bdc

搜索帮助