dial tcp: 本地地址类型不匹配 172.29.4.175

huangapple go评论86阅读模式
英文:

dial tcp: mismatched local address type 172.29.4.175

问题

我在以下代码中遇到了这个错误:dial tcp: mismatched local address type 172.29.4.175

有什么办法可以解决这个问题吗?除了http://oocms.org/question/763660/dial-with-a-specific-address-interface-golang,我在网上找不到其他有用的信息,但那个方法也没有起作用。

IP地址172.29.4.175目前是我的Macbook的Wi-Fi接口的IP地址。

package main

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

var url = "https://httpbin.org/get"

func main() {

	q := net.ParseIP("172.29.4.175")
	addr := &net.IPAddr{q, ""}

	var transport = &http.Transport{
		DialContext: (&net.Dialer{
			LocalAddr: addr,
		}).DialContext,
	}

	var httpclient = &http.Client{
		Transport: transport,
	}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println(err)
	}

	req.Header.Set("User-Agent", "Test-Agent")

	resp, err := httpclient.Do(req)
	fmt.Println(resp, err)
}

请注意,我只会翻译代码部分,不会回答关于翻译的问题。

英文:

I'm getting this error with the following code: dial tcp: mismatched local address type 172.29.4.175

Any idea on how to fix this? Couldn't find anything useful online other than http://oocms.org/question/763660/dial-with-a-specific-address-interface-golang but that didn't work.

The IP 172.29.4.175 is currently the IP of my Macbooks wifi interface.

package main

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

var url = "https://httpbin.org/get"

func main() {

	q := net.ParseIP("172.29.4.175")
	addr := &net.IPAddr{q, ""}

	var transport = &http.Transport{
		DialContext: (&net.Dialer{
			LocalAddr: addr,
		}).DialContext,
	}

	var httpclient = &http.Client{
		Transport: transport,
	}

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println(err)
	}

	req.Header.Set("User-Agent", "Test-Agent")

	resp, err := httpclient.Do(req)
	fmt.Println(resp, err)
}

答案1

得分: 5

几乎100%的情况下,HTTP Dial都会通过TCP连接。你只提供了一个IP地址,使用ip网络类型,但是TCP地址需要使用tcp网络类型和端口号。

你可以将net.TCPAddr替换为net.IPAddr,或者使用net.ResolveTCPAddr创建正确的类型。

addr := &net.TCPAddr{net.IP{172, 29, 4, 175}, 0, ""}

或者

addr, _ := net.ResolveTCPAddr("tcp", "172.29.4.175:0")
英文:

Nearly 100% of the time, an HTTP Dial is going to be connecting via TCP. You're only providing an IP address with the ip network type, yet a TCP address required the tcp network type and a port number.

You can either substitute net.TCPAddr for net.IPAddr, or start with net.ResolveTCPAddr to create the correct type.

addr := &net.TCPAddr{net.IP{172, 29, 4, 175}, 0, ""}

or

addr, _ := net.ResolveTCPAddr("tcp", "172.29.4.175:0")

huangapple
  • 本文由 发表于 2016年11月5日 03:04:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/40430098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定