Golang使用自定义IP请求https

可以自定义 TLSClientConfig 的 ServerName 字段,并使用自定义的 DialContext 函数来控制连接到指定 IP

代码如下

go 复制代码
func main() {
	// 定义目标站点的域名和IP地址
	domain := "www.baidu.com"
	ip := "183.2.172.42" // 该 IP 地址对应 baidu.com

	// 创建自定义的HTTP客户端
	client := &http.Client{

		Timeout: 5 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				ServerName: domain, // 设置服务器名
			},
			DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
				// 目标地址是指定的IP,使用自定义Dialer连接
				return (&net.Dialer{
					Timeout:   5 * time.Second,
					KeepAlive: 30 * time.Second,
				}).DialContext(ctx, "tcp", ip+":443")

			},

			TLSHandshakeTimeout: 5 * time.Second,
		},
	}

	// 发送HTTPS请求
	resp, err := client.Get("https://" + domain + "/")
	if err != nil {
		fmt.Printf("无法连接到 %s: %v\n", domain, err)
		return
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("无法读取响应: %v\n", err)
		return
	}

	// 输出响应内容
	fmt.Println("响应内容:", string(body))
}
相关推荐
ttwuai1 天前
Go开源后台管理系统推荐:怎么按技术栈和边界比较4个官方仓库?
golang·gin
codeejun1 天前
每日一Go·MySQL-5、锁机制全解析
云原生·golang
Achou.Wang1 天前
k8s中nginx worker process自动设置
后端·golang
2501_916007471 天前
苹果商店iOS应用上架费用全面解析:开发者计划与审核费用计算
android·ios·小程序·https·uni-app·iphone·webview
Lsetea1 天前
证书没到期却报certificate has expired:OpenSSL定位中间证书与系统时间
运维·https·ssl证书·openssl·证书链
2501_916008891 天前
如何实现iOS App代码混淆:SwiftShield使用指南
android·ios·小程序·https·uni-app·iphone·webview
SDWAN_Cheap1 天前
HTTPS到底加密了什么?
https·数据加密
2501_916008892 天前
怎么用 Godot 导出 iOS 应用并上架 App Store?签名字段该填什么?
android·ios·小程序·https·uni-app·iphone·webview
Lsetea2 天前
Nginx报No required SSL certificate was sent:mTLS客户端证书排查
运维·nginx·https·ssl·openssl
指尖的爷2 天前
ARM 架构 Ubuntu(RK3588/aarch64)go开发环境安装手册
ubuntu·架构·golang