ed557

学习笔记

golang发送HTTP请求时获取目标IP (server ip)

golang net/http库在发送http请求时会通过调用net下的Dialer建立TCP连接, net.Dialer 会在发起连接前执行通过ControlContext字段传入的一个函数, 我们可以通过这个函数获取ip、端口和网络名等信息。

https://cs.opensource.google/go/go/+/master:src/net/dial.go;l=110;drc=74b6a22057b393f198d2d86f4ea7504dacf390f5;bpv=0;bpt=1

示例代码:

package main

import (
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"syscall"
)

func customControl(network string, address string, conn syscall.RawConn) error {
	fmt.Printf("%s,%s\n", network, address)
	return nil
}

func main() {
	dialer := &net.Dialer{
		Control: customControl,
	}
	t := http.DefaultTransport.(*http.Transport).Clone()
	t.DialContext = dialer.DialContext

	c := &http.Client{
		Transport: t,
	}
	resp, _ := c.Get("https://www.baidu.com")
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("%s\n", body)
}

输出:

tcp4,14.215.177.39:443
<html>
<head>
        <script>
                location.replace(location.href.replace("https://","http://"));
        </script>
</head>
<body>
        <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>

我们可以在这个函数里记录每个http请求的实际ip地址,也可以在这里对请求IP做一些策略和检查,比如防范SSRF等等。

posted on 2022-11-15 21:24  ed557  阅读(609)  评论(0编辑  收藏  举报

导航