Created
January 19, 2025 01:08
-
-
Save mike-weiner/1f2ee9a90ab0086f9795aede4b4402d4 to your computer and use it in GitHub Desktop.
A small Go snippet demonstrating how to use a custom DNS resolver to lookup IPs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"net" | |
"time" | |
) | |
func main() { | |
customResolver := &net.Resolver{ | |
PreferGo: true, | |
Dial: func(ctx context.Context, network, address string) (net.Conn, error) { | |
return net.Dial(network, "1.1.1.1:53") | |
}, | |
} | |
timeout := 10 * time.Second | |
ctx, cancel := context.WithTimeout(context.Background(), timeout) | |
defer cancel() | |
ipAddrs, err := customResolver.LookupIPAddr(ctx, "example.com") | |
if err != nil { | |
if ctx.Err() == context.DeadlineExceeded { | |
fmt.Println("DNS lookup timed out!") | |
} else { | |
fmt.Println("Error:", err) | |
} | |
return | |
} | |
for _, ipAddr := range ipAddrs { | |
fmt.Printf("%s\n", ipAddr.String()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment