diff options
author | Mikael Magnusson <mikma@users.sourceforge.net> | 2021-01-13 23:31:35 +0100 |
---|---|---|
committer | Mikael Magnusson <mikma@users.sourceforge.net> | 2021-02-02 23:57:01 +0100 |
commit | 876011d0cfeb06d33336140c14e93f8be9a88ab2 (patch) | |
tree | 0a991dd9ab870f08253cd0a8329c70f430624c61 | |
parent | 48460703229d73fbacdd0d6b0d0f01a54f7ce751 (diff) |
tun: implement AddAddress
-rw-r--r-- | tun/netstack/tun.go | 39 |
1 files changed, 21 insertions, 18 deletions
diff --git a/tun/netstack/tun.go b/tun/netstack/tun.go index 6bdea23..e456bf6 100644 --- a/tun/netstack/tun.go +++ b/tun/netstack/tun.go @@ -108,26 +108,11 @@ func CreateNetTUN(localAddresses []net.IP, dnsServers []net.IP, mtu int) (tun.De return nil, nil, fmt.Errorf("CreateNIC: %v", tcpipErr) } for _, ip := range localAddresses { - if ip4 := ip.To4(); ip4 != nil { - tcpipErr = dev.stack.AddAddress(1, ipv4.ProtocolNumber, tcpip.Address(ip4)) - if tcpipErr != nil { - return nil, nil, fmt.Errorf("AddAddress(%v): %v", ip4, tcpipErr) - } - dev.hasV4 = true - } else { - tcpipErr = dev.stack.AddAddress(1, ipv6.ProtocolNumber, tcpip.Address(ip)) - if tcpipErr != nil { - return nil, nil, fmt.Errorf("AddAddress(%v): %v", ip4, tcpipErr) - } - dev.hasV6 = true + tcpipErr := (*Net)(dev).AddAddress(ip) + if tcpipErr != nil { + return nil, nil, fmt.Errorf("AddAddress(%v): %w", ip, tcpipErr) } } - if dev.hasV4 { - dev.stack.AddRoute(tcpip.Route{Destination: header.IPv4EmptySubnet, NIC: 1}) - } - if dev.hasV6 { - dev.stack.AddRoute(tcpip.Route{Destination: header.IPv6EmptySubnet, NIC: 1}) - } dev.events <- tun.EventUp return dev, (*Net)(dev), nil @@ -206,6 +191,24 @@ func convertToFullAddr(ip net.IP, port int) (tcpip.FullAddress, tcpip.NetworkPro } } +func (net *Net) AddAddress(ip net.IP) *tcpip.Error { + if ip4 := ip.To4(); ip4 != nil { + tcpipErr := net.stack.AddAddress(1, ipv4.ProtocolNumber, tcpip.Address(ip4)) + if tcpipErr == nil && !net.hasV4 { + net.hasV4 = true + net.stack.AddRoute(tcpip.Route{Destination: header.IPv4EmptySubnet, NIC: 1}) + } + return tcpipErr + } else { + tcpipErr := net.stack.AddAddress(1, ipv6.ProtocolNumber, tcpip.Address(ip)) + if tcpipErr == nil && !net.hasV6{ + net.hasV6 = true + net.stack.AddRoute(tcpip.Route{Destination: header.IPv6EmptySubnet, NIC: 1}) + } + return tcpipErr + } +} + func (net *Net) DialContextTCP(ctx context.Context, addr *net.TCPAddr) (*gonet.TCPConn, error) { if addr == nil { panic("todo: deal with auto addr semantics for nil addr") |