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