I just simply want to have golang http get request to use ipv4 only.
And the answers from golang force net/http client to use IPv4 / IPv6 is not working for me. Moreover, I found the following answer, which is not working for me either:
package main
import (
"fmt"
"net"
"net/http"
"time"
)
func main() {
// Create a transport object
transport := &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: false, // This ensures only IPv4 is used
}).Dial,
}
// Create an HTTP client with the custom transport
client := &http.Client{
Transport: transport,
}
// Create an HTTP GET request
req, err := http.NewRequest("GET", "https://ifconfig.me/", nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Send the request using the client
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Handle the response as needed
// ...
}
I'm still getting IPv6 return with it (from https://ifconfig.me/).
Any help please?
I'm having the same problem, I need to control http requests for IPV4 only or IPV6 only. This is my solution:
client := &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, netType, addr)
},
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: 6 * time.Second,
},
}
resp, err := client.Get("http://yourwebsite")
netType I use tcp4 or tcp6
For more information, https://gist.github.com/Integralist/8a9cb8924f75ae42487fd877b03360e2?permalink_comment_id=4863513 will be a good newbie guide.