Dial with a specific address / interface ? Golang

2020-02-23 20:44发布

问题:

I have two network interfaces on my computer ( eth0 and eth1) and I'm trying to Dial a connection using a specific one (eth1). Given the statement that Go is a system language I assumed so but is it really possible with the current standard library?

So far I've got to get the interface by name InterfaceByName (eth1) then I range over the Addrs method and extracted the first address [0] which seems to be the source address of eth1 interface (e.g. xxx.xxx.xxx/24); the other one is the ipv6 address.
I've created a new Dialer and set Dialer.LocalAddr with the address extracted. However I get this error mismatched local address type wich seems related to dialSingle function from dial.go

Edit Some code:

package main
import (
        "net"
        "log"
)

func main(){
        ief, err := net.InterfaceByName("eth1")
        if err !=nil{
                log.Fatal(err)
        }
        addrs, err := ief.Addrs()
        if err !=nil{
                log.Fatal(err)
        }
        d := net.Dialer{LocalAddr: addrs[0]}
        _, err = d.Dial("tcp", "google.com:80")
        if err != nil {
                log.Fatal(err)
        }
}

Output: 2014/12/10 17:11:48 dial tcp 216.58.208.32:80: mismatched local address type ip+net

回答1:

When you pull the address from an interface, it's of type *net.IPnet wrapped in a net.Addr interface, which contains and address and netmask not an address and port. You can use the IP address however to create a new TCPAddr after asserting it as a *net.IPnet

    ief, err := net.InterfaceByName("eth1")
    if err !=nil{
            log.Fatal(err)
    }
    addrs, err := ief.Addrs()
    if err !=nil{
            log.Fatal(err)
    }

    tcpAddr := &net.TCPAddr{
        IP: addrs[0].(*net.IPNet).IP,
    }