用特定的地址/界面拨号? Golang [英] Dial with a specific address / interface ? Golang

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

问题描述

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



到目前为止,我必须通过名称获取界面 InterfaceByName eth1 )然后我通过 Addrs 方法,并提取第一个地址[0],这似乎是成为eth1接口的源地址(例如xxx.xxx.xxx/24);另一个是ipv6地址。

我创建了一个新的 Dialer 并设置 Dialer.LocalAddr ,并提取地址。但是我得到这个错误不匹配的本地地址类型,这似乎与 dial.go



编辑
部分代码:

 包主
进口(

记录


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 code>接口,其中包含地址和网络掩码不是地址和端口。然后,您可以使用IP地址在将其设为 * net.IPnet



<$ p $后创建一个新的TCPAddr p> 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,
}


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

解决方案

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆