Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dial with a specific address / interface ? Golang

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

like image 248
The user with no hat Avatar asked Dec 10 '14 21:12

The user with no hat


1 Answers

When you pull the address from an interface, it's of type *net.IPnet wrapped in a net.Addr interface, which contains an address and netmask NOT an address and port. You can use the IP address, however, you have 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,
    }
like image 139
JimB Avatar answered Nov 05 '22 03:11

JimB