Home > OS >  How to extract the connected local ip address using http.Client in Go?
How to extract the connected local ip address using http.Client in Go?

Time:12-23

My PC has multiple IP addresses(ex: 10.1.1.20, 192.168.123.30, ...).

Can I extract the connected local ip address when connecting to remote server using http.Client?

If this is not possible with http.Client, is there any other possible way?

package main

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

func main() {
    req, err := http.NewRequest("GET", "https://www.google.com", nil)
    if err != nil {
        panic(err)
    }

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    // extract the local ip address???
    // getsockname(?????)

    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    fmt.Printf("StatusCode=%v\n", resp.StatusCode)
    fmt.Printf("%v\n", string(data))
}

CodePudding user response:

You can either:

But in both case, the fact that you are in the middle of using an http.Client and making a GET would not matter: you could get those IP addresses independently.

CodePudding user response:

You can provide your own Transport implementation that extracts the outgoing local IP address right after establishing the TCP connection, e.g. like this:

    client := &http.Client{
        Transport: &http.Transport{
            Dial: func(network, addr string) (net.Conn, error) {
                conn, err := net.Dial(network, addr)
                if err == nil {
                    localAddr := conn.LocalAddr().(*net.TCPAddr)
                    fmt.Println("LOCAL IP:", localAddr.IP)
                }

                return conn, err
            },
        },
    }
  • Related