本文介绍了使用特定地址/接口拨号?戈朗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的计算机上有两个网络接口(eth0 和 eth1),我正在尝试使用特定的网络接口(eth1)拨号连接.鉴于 Go 是一种系统语言的声明,我认为是这样,但是当前的标准库真的有可能吗?

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?

到目前为止,我必须按名称获取接口 InterfaceByName (eth1) 然后我在 Addrs 方法提取第一个地址[0],这似乎是eth1接口的源地址(例如xxx.xxx.xxx/24);另一个是 ipv6 地址.
我创建了一个新的 Dialer 并设置了 Dialer.LocalAddr 加上地址提取.但是我收到此错误 mismatched local address type 似乎与 dial.go

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

编辑一些代码:

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)
        }
}

输出:2014/12/10 17:11:48 dial tcp 216.58.208.32:80: 本地地址类型ip+net不匹配

推荐答案

当你从接口拉取地址时,它的类型是 *net.IPnet 包裹在 net.Addr 接口,其中包含地址和网络掩码NOT 地址和端口.您可以使用 IP 地址,但是,您必须在将其声明为 *net.IPnet

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,
    }

这篇关于使用特定地址/接口拨号?戈朗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:36