golang udp 指定本地地址和端口

前端之家收集整理的这篇文章主要介绍了golang udp 指定本地地址和端口前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

指定本地地址为127.0.0.1 端口7770

localip := net.ParseIP("127.0.0.1")
    remoteip := net.ParseIP("127.0.0.1")
    lAddr := &net.UDPAddr{IP: localip,Port: 7770}
    rAddr := &net.UDPAddr{IP: remoteip,Port: 9130}
    conn,err := net.DialUDP("udp",lAddr,rAddr)
    if err != nil {
        fmt.Println(err)
    }
    defer conn.Close()
    conn.Write([]byte("hello"))

go net标准库中DialUDP的实现

// DialUDP connects to the remote address raddr on the network net,// which must be "udp","udp4",or "udp6".  If laddr is not nil,it is
// used as the local address for the connection.
func DialUDP(net string,laddr,raddr *UDPAddr) (*UDPConn,error) {
    switch net {
    case "udp","udp6":
    default:
        return nil,&OpError{Op: "dial",Net: net,Source: laddr.opAddr(),Addr: raddr.opAddr(),Err: UnknownNetworkError(net)}
    }
    if raddr == nil {
        return nil,Addr: nil,Err: errMissingAddress}
    }
    c,err := dialUDP(context.Background(),net,raddr)
    if err != nil {
        return nil,Err: err}
    }
    return c,nil
}
原文链接:https://www.f2er.com/go/187174.html

猜你在找的Go相关文章