nic.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package tun
  2. import (
  3. "github.com/v2fly/v2ray-core/v5/app/router/routercommon"
  4. "gvisor.dev/gvisor/pkg/tcpip"
  5. "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
  6. "gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
  7. "gvisor.dev/gvisor/pkg/tcpip/stack"
  8. )
  9. func CreateNIC(nicID tcpip.NICID, linkEndpoint stack.LinkEndpoint) StackOption {
  10. return func(s *stack.Stack) error {
  11. if err := s.CreateNICWithOptions(nicID, linkEndpoint,
  12. stack.NICOptions{
  13. Disabled: false,
  14. QDisc: nil,
  15. }); err != nil {
  16. return newError("failed to create NIC:", err)
  17. }
  18. return nil
  19. }
  20. }
  21. func AddProtocolAddress(id tcpip.NICID, ips []*routercommon.CIDR) StackOption {
  22. return func(s *stack.Stack) error {
  23. for _, ip := range ips {
  24. tcpIpAddr := tcpip.AddrFrom4Slice(ip.Ip)
  25. protocolAddress := tcpip.ProtocolAddress{
  26. AddressWithPrefix: tcpip.AddressWithPrefix{
  27. Address: tcpIpAddr,
  28. PrefixLen: int(ip.Prefix),
  29. },
  30. }
  31. switch tcpIpAddr.Len() {
  32. case 4:
  33. protocolAddress.Protocol = ipv4.ProtocolNumber
  34. case 16:
  35. protocolAddress.Protocol = ipv6.ProtocolNumber
  36. default:
  37. return newError("invalid IP address length:", tcpIpAddr.Len())
  38. }
  39. if err := s.AddProtocolAddress(id, protocolAddress, stack.AddressProperties{}); err != nil {
  40. return newError("failed to add protocol address:", err)
  41. }
  42. }
  43. return nil
  44. }
  45. }