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", "udp4", "udp6":
    default:
        return nil, &OpError{Op: "dial", Net: net, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: UnknownNetworkError(net)}
    }
    if raddr == nil {
        return nil, &OpError{Op: "dial", Net: net, Source: laddr.opAddr(), Addr: nil, Err: errMissingAddress}
    }
    c, err := dialUDP(context.Background(), net, laddr, raddr)
    if err != nil {
        return nil, &OpError{Op: "dial", Net: net, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: err}
    }
    return c, nil
}

你可能感兴趣的:(Golang,Golang学习笔记)