英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论