Golang 中网络请求使用指定网卡

当用户发起一个网络请求时,流量会通过默认的网卡接口流出与流入,但有时需要将流量通过指定的网卡进行流出流入,这时我们可能需要进行一些额外的开发工作,对其实现主要用到了 Dialer.Control 配置项。

type Dialer struct {

// If Control is not nil, it is called after creating the network
// connection but before actually dialing.
//
// Network and address parameters passed to Control method are not
// necessarily the ones passed to Dial. For example, passing "tcp" to Dial
// will cause the Control function to be called with "tcp4" or "tcp6".
Control func(network, address string, c syscall.RawConn) error
}

可以看到这是一个函数类型的参数。

环境

当前系统一共两个网卡 ens33ens160 ,ip地址分别为 192.168.3.80192.168.3.48

➜  ~ ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
      inet 192.168.3.80 netmask 255.255.255.0 broadcast 192.168.3.255
      inet6 fe80::8091:2406:c51e:ecb9 prefixlen 64 scopeid 0x20<link>
      ether 00:0c:29:4f:05:90 txqueuelen 1000 (Ethernet)
      RX packets 4805008 bytes 826619853 (826.6 MB)
      RX errors 0 dropped 104152 overruns 0 frame 0
      TX packets 732513 bytes 284605386 (284.6 MB)
      TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
      inet 192.168.3.48 netmask 255.255.255.0 broadcast 192.168.3.255
      inet6 fe80::259a:d8d4:80a9:7fa4 prefixlen 64 scopeid 0x20<link>
      ether 00:0c:29:4f:05:9a txqueuelen 1000 (Ethernet)
      RX packets 4158530 bytes 746167179 (746.1 MB)
      RX errors 1 dropped 106875 overruns 0 frame 0
      TX packets 351616 bytes 149235606 (149.2 MB)
      TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
      inet 127.0.0.1 netmask 255.0.0.0
      inet6 ::1 prefixlen 128 scopeid 0x10<host>
      loop txqueuelen 1000 (Local Loopback)
      RX packets 426742 bytes 80978543 (80.9 MB)
      RX errors 0 dropped 0 overruns 0 frame 0
      TX packets 426742 bytes 80978543 (80.9 MB)
      TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

路由表记录

➜  ~ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.3.1     0.0.0.0         UG    100    0        0 ens33
0.0.0.0         192.168.3.1     0.0.0.0         UG    101    0        0 ens160
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 ens33
192.168.3.0     0.0.0.0         255.255.255.0   U     100    0        0 ens33
192.168.3.0     0.0.0.0         255.255.255.0   U     101    0        0 ens160
​

从最后两条路由记录可以看到对于 192.168.3.0/24 这个段的流量会匹配的两个物理网卡,但由于配置的 Metric 的优先级比较的高,因此最终流量只会走网卡 ens33

Continue reading