我的机器上有几个公共 IP 地址。我想指定哪个用于请求。
我可以使用 curl 来做到这一点:
curl --interface 111.222.333.444 https://www.iplocation.net/find-ip-address | grep "Your IP address"
111.222.333.444我用来向 Internet 发出请求的本地 IP 地址之一在哪里。
如何使用golang?
这个方法...
package main
import (
"bytes"
"fmt"
"github.com/PuerkitoBio/goquery"
"io/ioutil"
"net"
"net/http"
"os"
"time"
)
func main() {
var localAddr = "111.222.333.444"
localAddress, _ := net.ResolveTCPAddr("tcp", localAddr)
// Create a transport like http.DefaultTransport, but with a specified localAddr
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
LocalAddr: localAddress,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
}
client := &http.Client{
Transport: transport,
}
response, err := client.Get("https://www.whatismyip.com/")
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
var contentsStr = string(contents)
fmt.Printf("%s\n", contentsStr)
var doc = DocByHtmlString(contentsStr)
doc.Find("div").Each(func(i int, s *goquery.Selection) {
attr, exists := s.Attr("class")
if exists {
if attr == "ip" {
fmt.Println(s.Text())
fmt.Println("expected ip is " + localAddr)
}
}
})
}
}
func DocByHtmlString(html string) *goquery.Document {
doc, err := goquery.NewDocumentFromReader(bytes.NewBufferString(html))
if err != nil {
panic(err)
}
return doc
}
...总是给我以下结果:
Your IP Address Is: 555.666.777.888 // main IP address on my machine
expected ip is 111.222.333.444
繁星淼淼
相关分类