dongyun6003
dongyun6003
2016-11-04 14:43

net.IP没有实现net.Addr(缺少网络方法)

I have the following code. I'm getting this error:

testdl.go:17: cannot use q (type net.IP) as type net.Addr in field value: net.IP does not implement net.Addr (missing Network method)

Any idea how to put a hardcoded IP into LocalAddr?

package main

import (
    "fmt"
    "net"
    "net/http"
)

var url = "http://URL/api.xml"

func main() {

    q := net.ParseIP("192.168.0.1")

    var transport = &http.Transport{
        Dial: (&net.Dialer{
            LocalAddr: q,
        }).Dial,
    }
    var httpclient = &http.Client{
        Transport: transport,
    }

    response, err := httpclient.Get(url)
    fmt.Println(response)
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dragon071111 dragon071111 5年前

    According to the documentation, indeed the IP type does not implement Addr. However, the type IPAddr does:

    type IPAddr struct {
        IP   IP
        Zone string // IPv6 scoped addressing zone
    }
    

    Therefore, your code becomes:

    q := net.ParseIP("192.168.0.1")
    addr := &net.IPAddr{q,""}
    
    var transport = &http.Transport{
        Dial: (&net.Dialer{
            LocalAddr: addr,
        }).Dial,
    }
    
    点赞 评论 复制链接分享
  • dongyuyi5680 dongyuyi5680 5年前

    Use the Docs, Luke...

    https://golang.org/pkg/net/#ResolveIPAddr

    If you use the IPAddr struct, that should solve your problem.

    点赞 评论 复制链接分享

为你推荐