Created
April 7, 2017 01:33
-
-
Save zweite/4d3c63f3fb42d33debc86099be652b3d to your computer and use it in GitHub Desktop.
networking interface http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net | |
import ( | |
"errors" | |
"net" | |
"strings" | |
"time" | |
) | |
// 给定网卡名称,获取该网卡出口链接 | |
func GetConnByName(name, network, address string) (conn net.Conn, err error) { | |
intf, err := net.InterfaceByName(name) | |
if err != nil { | |
return nil, err | |
} | |
addrs, err := intf.Addrs() | |
if err != nil { | |
return nil, err | |
} | |
if len(addrs) < 2 { | |
return nil, errors.New("not addrs") | |
} | |
addr := strings.Split(addrs[1].String(), "/")[0] | |
ipAddr, err := net.ResolveTCPAddr("tcp", addr+":0") | |
if err != nil { | |
return | |
} | |
dialer := net.Dialer{ | |
Timeout: time.Second * 10, | |
LocalAddr: ipAddr, | |
KeepAlive: time.Second * 60, | |
} | |
return dialer.Dial(network, address) | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net | |
import ( | |
"fmt" | |
"io/ioutil" | |
"net" | |
"net/http" | |
"testing" | |
) | |
// 测试出口网卡是否为选定的网卡外网IP | |
func TestConnByInterface(t *testing.T) { | |
client := new(http.Client) | |
client.Transport = &http.Transport{ | |
Dial: func(network, addr string) (net.Conn, error) { | |
return GetConnByName("ppp0", network, addr) | |
}, | |
} | |
resp, err := client.Get("http://ip.chinaz.com/getip.aspx") | |
if err != nil { | |
t.Fatal(err) | |
} | |
data, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
t.Fatal(err) | |
} | |
fmt.Println(string(data)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment