dongpu6141 2016-11-04 19:04
浏览 29
已采纳

拨打tcp:本地地址类型不匹配172.29.4.175

I'm getting this error with the following code: dial tcp: mismatched local address type 172.29.4.175

Any idea on how to fix this? Couldn't find anything useful online other than http://oocms.org/question/763660/dial-with-a-specific-address-interface-golang but that didn't work.

The IP 172.29.4.175 is currently the IP of my Macbooks wifi interface.

package main

import (
    "fmt"
    "net"
    "net/http"
)

var url = "https://httpbin.org/get"

func main() {

    q := net.ParseIP("172.29.4.175")
    addr := &net.IPAddr{q, ""}

    var transport = &http.Transport{
        DialContext: (&net.Dialer{
            LocalAddr: addr,
        }).DialContext,
    }

    var httpclient = &http.Client{
        Transport: transport,
    }

    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println(err)
    }

    req.Header.Set("User-Agent", "Test-Agent")

    resp, err := httpclient.Do(req)
    fmt.Println(resp, err)
}
  • 写回答

1条回答 默认 最新

  • dongqufi82315 2016-11-04 19:10
    关注

    Nearly 100% of the time, an HTTP Dial is going to be connecting via TCP. You're only providing an IP address with the ip network type, yet a TCP address required the tcp network type and a port number.

    You can either substitute net.TCPAddr for net.IPAddr, or start with net.ResolveTCPAddr to create the correct type.

    addr := &net.TCPAddr{net.IP{172, 29, 4, 175}, 0, ""}
    

    or

    addr, _ := net.ResolveTCPAddr("tcp", "172.29.4.175:0")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型