rust-lang / socket2

Advanced configuration options for sockets.
https://docs.rs/socket2
Apache License 2.0
673 stars 221 forks source link

QUESTION: How to special `laddr` when dialing connection? #478

Closed jjeffcaii closed 10 months ago

jjeffcaii commented 10 months ago

In Golang, we can use codes below to specify the local addr:

    // https://cs.opensource.google/go/go/+/refs/tags/go1.21.3:src/net/udpsock.go;l=290
    srcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 9982}
    dstAddr := &net.UDPAddr{IP: net.ParseIP("207.148.70.129"), Port: 9981}
    conn, err := net.DialUDP("udp", srcAddr, dstAddr)
    if err != nil {
        fmt.Println(err)
    }

I didn't find similar methods in the socket2 pkg, can anyone help?

the8472 commented 10 months ago

socket2 mostly provides pretty straight-forward mappings to underlying OS APIs. The operation you're looking for is bind, which is also called bind in socket2.

See the socket(7) man page or wikipedia for a high level overview of the available functions.

As socket2's top level docs say

If you don’t know how to create a socket using libc/system calls then this crate is not for you. Most, if not all, functions directly relate to the equivalent system call with no error handling applied

Thomasdezeeuw commented 10 months ago

laddr stands for local address. You first need to bind(2) the socket to a local address, then call connect(2).

As @the8472 mentioned If you want to use socket2 you need some knowledge of the underlying system calls, for which the linked manual pages and Wikipedia are a good starting point. Of course there is always the awesome Beej network guide: https://beej.us/guide/bgnet/ (arguably the best learning resource for using BSD sockets).

jjeffcaii commented 10 months ago

Thanks! ❤️