github.com/labulakalia/water@v0.0.5-0.20231118024244-f351ca6784b6/if.go (about) 1 package water 2 3 import ( 4 "errors" 5 "io" 6 ) 7 8 // Interface is a TUN/TAP interface. 9 // 10 // MultiQueue(Linux kernel > 3.8): With MultiQueue enabled, user should hold multiple 11 // interfaces to send/receive packet in parallel. 12 // Kernel document about MultiQueue: https://www.kernel.org/doc/Documentation/networking/tuntap.txt 13 type Interface struct { 14 isTAP bool 15 io.ReadWriteCloser 16 name string 17 } 18 19 // DeviceType is the type for specifying device types. 20 type DeviceType int 21 22 // TUN and TAP device types. 23 const ( 24 _ = iota 25 TUN 26 TAP 27 ) 28 29 // Config defines parameters required to create a TUN/TAP interface. It's only 30 // used when the device is initialized. A zero-value Config is a valid 31 // configuration. 32 type Config struct { 33 // DeviceType specifies whether the device is a TUN or TAP interface. A 34 // zero-value is treated as TUN. 35 DeviceType DeviceType 36 37 // PlatformSpecificParams defines parameters that differ on different 38 // platforms. See comments for the type for more details. 39 PlatformSpecificParams 40 } 41 42 func defaultConfig() Config { 43 return Config{ 44 DeviceType: TUN, 45 PlatformSpecificParams: defaultPlatformSpecificParams(), 46 } 47 } 48 49 var zeroConfig Config 50 51 // New creates a new TUN/TAP interface using config. 52 func New(config Config) (ifce *Interface, err error) { 53 if zeroConfig == config { 54 config = defaultConfig() 55 } 56 if config.PlatformSpecificParams == zeroConfig.PlatformSpecificParams { 57 config.PlatformSpecificParams = defaultPlatformSpecificParams() 58 } 59 switch config.DeviceType { 60 case TUN, TAP: 61 return openDev(config) 62 default: 63 return nil, errors.New("unknown device type") 64 } 65 } 66 67 // IsTUN returns true if ifce is a TUN interface. 68 func (ifce *Interface) IsTUN() bool { 69 return !ifce.isTAP 70 } 71 72 // IsTAP returns true if ifce is a TAP interface. 73 func (ifce *Interface) IsTAP() bool { 74 return ifce.isTAP 75 } 76 77 // Name returns the interface name of ifce, e.g. tun0, tap1, tun0, etc.. 78 func (ifce *Interface) Name() string { 79 return ifce.name 80 }