Documentation
¶
Overview ¶
Package vmnet configures logical networks provided by Apple's vmnet framework.
Index ¶
- Variables
- func BridgedInterfaces() ([]string, error)
- type Error
- type Interface
- func (i *Interface) MACAddress() net.HardwareAddr
- func (i *Interface) MTU() int
- func (i *Interface) MaxPacketSize() int
- func (i *Interface) ReadPacket(ctx context.Context, frame []byte) (int, error)
- func (i *Interface) ReadPackets(ctx context.Context, frames [][]byte) (int, error)
- func (i *Interface) Stop() error
- func (i *Interface) TSOEnabled() bool
- func (i *Interface) VirtioHeaderEnabled() bool
- func (i *Interface) WritePacket(frame []byte) error
- func (i *Interface) WritePackets(frames [][]byte) (int, error)
- type InterfaceOption
- type Mode
- type Network
- type NetworkConfiguration
- type NetworkConfigurationOption
- func WithDHCPDisabled() NetworkConfigurationOption
- func WithDHCPReservation(mac net.HardwareAddr, address netip.Addr) NetworkConfigurationOption
- func WithDNSProxyDisabled() NetworkConfigurationOption
- func WithExternalInterface(name string) NetworkConfigurationOption
- func WithIPv4Subnet(prefix netip.Prefix) NetworkConfigurationOption
- func WithIPv6Prefix(prefix netip.Prefix) NetworkConfigurationOption
- func WithMTU(mtu int) NetworkConfigurationOption
- func WithNAT44Disabled() NetworkConfigurationOption
- func WithNAT66Disabled() NetworkConfigurationOption
- func WithPortForwarding(network string, externalPort uint16, destination netip.AddrPort) NetworkConfigurationOption
- func WithRouterAdvertisementDisabled() NetworkConfigurationOption
- type NetworkSerialization
- type NetworkService
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnsupportedOSVersion is returned when an API requires a newer macOS version. ErrUnsupportedOSVersion = macos.ErrUnsupportedOSVersion // ErrBuildTargetOSVersion is returned when the build SDK does not include an API. ErrBuildTargetOSVersion = macos.ErrBuildTargetOSVersion )
Functions ¶
func BridgedInterfaces ¶
BridgedInterfaces returns the physical interface names eligible for bridged mode. It requires macOS 26 and newer. An empty slice means no eligible interfaces.
Types ¶
type Interface ¶
type Interface struct {
// contains filtered or unexported fields
}
Interface exchanges Ethernet frames on a Network or a bridged physical interface. WithInterfaceVirtioHeader adds a raw Virtio network header to each packet. Copies share one lifetime. Call Stop when finished. Its zero value is not usable.
func StartBridgedInterface ¶
func StartBridgedInterface(name string, opts ...InterfaceOption) (*Interface, error)
StartBridgedInterface starts an interface bridged to the named physical interface. BridgedInterfaces lists eligible names. It requires macOS 26 and newer. The returned interface must be stopped. On error it returns nil after attempting cleanup and includes any cleanup failure.
func StartInterfaceWithNetwork ¶
func StartInterfaceWithNetwork(n *Network, opts ...InterfaceOption) (*Interface, error)
StartInterfaceWithNetwork starts an interface without consuming the Network. It requires macOS 26 and newer. The returned interface must be stopped. On error it returns nil after attempting cleanup and includes any cleanup failure.
func (*Interface) MACAddress ¶
func (i *Interface) MACAddress() net.HardwareAddr
MACAddress returns a copy of the address reported by vmnet, or nil if none was reported.
func (*Interface) MTU ¶
MTU returns the interface MTU reported by vmnet, without Ethernet or Virtio headers. Unlike MaxPacketSize, it does not grow when TSO is enabled. It returns zero for a nil or uninitialized Interface.
See: https://developer.apple.com/documentation/vmnet/vmnet_mtu_key?language=objc
func (*Interface) MaxPacketSize ¶
MaxPacketSize returns the maximum Ethernet frame size, including Ethernet headers. When WithInterfaceVirtioHeader is enabled, it also includes the 12-byte Virtio header.
func (*Interface) ReadPacket ¶
ReadPacket waits for one frame. The buffer must hold MaxPacketSize bytes. WithInterfaceVirtioHeader includes the Virtio header in the buffer and byte count. A canceled context or Stop interrupts the wait. Concurrent readers share packets.
func (*Interface) ReadPackets ¶
ReadPackets reads Ethernet frames into frames and returns the number read. It waits for at least one frame, but does not wait to fill the batch. A read may return fewer frames than fit, even when more frames are queued. With WithInterfaceVirtioHeader enabled, each frame starts with a 12-byte Virtio header, which is included in its returned length.
Each buffer must have capacity for Interface.MaxPacketSize bytes. On success, ReadPackets sets the lengths of frames[:n] to the received frame lengths. The same buffers can be passed to the next call without resetting their lengths. The buffers must not overlap. The caller must not use frames or its buffers during the call, and ReadPackets does not retain them after it returns.
Canceling ctx or calling Interface.Stop interrupts a blocked read, including a read waiting for another reader to finish. On an open interface, an empty batch returns (0, nil).
See https://developer.apple.com/documentation/vmnet/vmnet_read(_:_:_:)?language=objc
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/Code-Hex/vz/v4/vmnet"
)
func main() {
config, err := vmnet.NewNetworkConfiguration(vmnet.ModeHost)
if err != nil {
fmt.Println(err)
return
}
network, err := vmnet.NewNetwork(config)
if err != nil {
fmt.Println(err)
return
}
iface, err := vmnet.StartInterfaceWithNetwork(network)
if err != nil {
fmt.Println(err)
return
}
defer iface.Stop()
frames := make([][]byte, 32)
for j := range frames {
frames[j] = make([]byte, 0, iface.MaxPacketSize())
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for {
n, err := iface.ReadPackets(ctx, frames)
if err != nil {
fmt.Println(err)
return
}
for _, frame := range frames[:n] {
fmt.Printf("received %d bytes\n", len(frame))
}
// Copy any frames you need to keep before the next read reuses the buffers.
}
}
Output:
func (*Interface) Stop ¶
Stop interrupts readers and stops the interface. It releases local resources even if the native stop fails. Repeated calls return the result of the first call without retrying.
func (*Interface) TSOEnabled ¶
TSOEnabled reports whether the interface was started with TCP segmentation offload. It returns false for a nil or uninitialized interface.
See https://developer.apple.com/documentation/vmnet/vmnet_enable_tso_key
func (*Interface) VirtioHeaderEnabled ¶
VirtioHeaderEnabled reports whether the interface was started with raw Virtio headers. It returns false for a nil or uninitialized interface.
See https://developer.apple.com/documentation/vmnet/vmnet_enable_virtio_header_key
func (*Interface) WritePacket ¶
WritePacket synchronously sends a frame and does not retain its buffer. WithInterfaceVirtioHeader requires frame to start with a 12-byte Virtio header.
func (*Interface) WritePackets ¶
WritePackets sends Ethernet frames and returns the number sent. It checks every frame before sending any, then splits the frames into native batches as needed. Each frame must contain between 1 and min(MaxPacketSize(), 256000) bytes. With WithInterfaceVirtioHeader enabled, each frame must start with a 12-byte Virtio header, which counts toward these size limits.
On error, n counts only frames confirmed by successful native calls. The failed call may have sent additional frames, so retrying frames[n:] can send duplicates. Concurrent writers may interleave their batches.
The caller must not change frames or its buffers during the call. WritePackets does not retain them after it returns. On an open interface, an empty batch returns (0, nil).
See https://developer.apple.com/documentation/vmnet/vmnet_write(_:_:_:)?language=objc
Example ¶
package main
import (
"encoding/binary"
"fmt"
"github.com/Code-Hex/vz/v4/vmnet"
)
func main() {
config, err := vmnet.NewNetworkConfiguration(vmnet.ModeHost)
if err != nil {
fmt.Println(err)
return
}
network, err := vmnet.NewNetwork(config)
if err != nil {
fmt.Println(err)
return
}
iface, err := vmnet.StartInterfaceWithNetwork(network)
if err != nil {
fmt.Println(err)
return
}
defer iface.Stop()
frames := make([][]byte, 2)
for j := range frames {
frame := make([]byte, 60)
copy(frame[:6], []byte{255, 255, 255, 255, 255, 255})
copy(frame[6:12], iface.MACAddress())
// EtherType 0x88b5 is reserved for local experimental use.
binary.BigEndian.PutUint16(frame[12:14], 0x88b5)
copy(frame[14:], fmt.Sprintf("packet %d", j))
frames[j] = frame
}
if n, err := iface.WritePackets(frames); err != nil {
// The failed native call may have sent more than n frames. Do not retry
// frames[n:] unless the protocol can handle duplicates.
fmt.Printf("sent at least %d frames: %v\n", n, err)
return
}
}
Output:
type InterfaceOption ¶
type InterfaceOption func(*interfaceConfiguration)
InterfaceOption configures an interface before it starts. Options are applied in order, so the last value for a capability takes precedence.
func WithInterfaceChecksumOffload ¶
func WithInterfaceChecksumOffload(enabled bool) InterfaceOption
WithInterfaceChecksumOffload controls IPv4 header, TCP, and UDP checksum offload. Checksum offload is disabled by default.
func WithInterfaceIsolation ¶
func WithInterfaceIsolation(enabled bool) InterfaceOption
WithInterfaceIsolation controls communication with other vmnet interfaces. On a Network, isolation applies to peers that also enable isolation. A bridged interface with isolation enabled cannot communicate with other vmnet interfaces. Isolation is disabled by default.
func WithInterfaceMACAllocation ¶
func WithInterfaceMACAllocation(enabled bool) InterfaceOption
WithInterfaceMACAllocation controls whether vmnet generates a MAC address. MAC allocation is enabled by default.
func WithInterfaceTSO ¶
func WithInterfaceTSO(enabled bool) InterfaceOption
WithInterfaceTSO controls TCP segmentation offload, which is disabled by default. When enabled, the peer must support large TCP frames.
func WithInterfaceVirtioHeader ¶
func WithInterfaceVirtioHeader(enabled bool) InterfaceOption
WithInterfaceVirtioHeader controls whether packets include a 12-byte Virtio network header before the Ethernet frame. It is disabled by default. Read and write methods pass the header through unchanged. The caller or peer must handle any checksum and segmentation work specified by received headers. Writes must provide valid header metadata. This option cannot be enabled with WithInterfaceChecksumOffload.
A socket peer must understand this packet format. Plain Ethernet connections, including QEMU stream/socket networking, VZ file-handle attachments, and krunkit's Unix datagram backend, cannot consume these packets without conversion.
type Network ¶
type Network pointer
Network is a logical network shared by one or more vmnet attachments. Create it with NewNetwork. Its zero value is not usable.
func NewNetwork ¶
func NewNetwork(config *NetworkConfiguration) (*Network, error)
NewNetwork reserves a logical network using config without consuming it. The reservation lasts while the network or its attachments remain in use. DHCP reservations are checked against the actual subnet before the network is returned. It requires macOS 26 and newer.
func NewNetworkWithSerialization ¶
func NewNetworkWithSerialization(serialization *NetworkSerialization) (*Network, error)
NewNetworkWithSerialization creates another reference to the same logical network without consuming the serialization. It requires macOS 26 and newer.
func ReceiveNetwork ¶
ReceiveNetwork obtains a reference to the logical network published by ShareNetwork through the launchd Mach service named name.
peerRequirement is a nonempty Apple code signing requirement expression checked against the server executable. The server independently checks the client's signature against the requirement passed to ShareNetwork.
ctx must be non-nil. Use a deadline to bound the request, including service startup and authentication. After ReceiveNetwork returns successfully, cancellation of ctx does not affect the returned network.
Pass the network to StartInterfaceWithNetwork or to vz.NewVMNetNetworkDeviceAttachment to connect a VM. XPC transfers the network reference, not VM packets. The sharing service and its process must remain running while the client uses the network.
ReceiveNetwork requires macOS 26 and newer.
func (*Network) CopySerialization ¶
func (n *Network) CopySerialization() (*NetworkSerialization, error)
CopySerialization copies the network's XPC representation without consuming the network. The serialization keeps its source network alive. It requires macOS 26 and newer.
func (*Network) IPv4Subnet ¶
IPv4Subnet returns the reserved IPv4 subnet, including an automatically selected subnet when none was configured. It requires macOS 26 and newer.
type NetworkConfiguration ¶
type NetworkConfiguration struct {
// contains filtered or unexported fields
}
NetworkConfiguration configures a logical network shared by vmnet attachments. Create it with NewNetworkConfiguration. Its settings are immutable after construction, and its zero value is not usable.
func NewNetworkConfiguration ¶
func NewNetworkConfiguration(mode Mode, opts ...NetworkConfigurationOption) (*NetworkConfiguration, error)
NewNetworkConfiguration creates a configuration with DHCP and IPv6 router advertisements enabled, an automatically selected IPv4 subnet, and a random IPv6 ULA prefix, unless overridden by options. Omitted service options preserve vmnet defaults for the selected mode. Options are applied in order before native allocation. A nil or invalid option returns an error. Repeated options use the last value for each setting, MAC address, or port forwarding rule, but an invalid option always returns an error. DHCP reservations are validated against the final IPv4 subnet. It requires macOS 26 and newer.
type NetworkConfigurationOption ¶
type NetworkConfigurationOption func(*networkConfigurationOptions) error
NetworkConfigurationOption configures a network before native allocation. Use options such as WithMTU with NewNetworkConfiguration.
func WithDHCPDisabled ¶
func WithDHCPDisabled() NetworkConfigurationOption
WithDHCPDisabled disables vmnet's DHCP server. Guests need static IPv4 configuration or another DHCP server.
func WithDHCPReservation ¶
func WithDHCPReservation(mac net.HardwareAddr, address netip.Addr) NetworkConfigurationOption
WithDHCPReservation reserves an IPv4 address for a unicast Ethernet MAC address. It copies mac when the option is created. Repeated reservations for the same MAC use the last address.
The address must belong to the final IPv4 subnet and cannot be its network, host, or broadcast address, regardless of option order. With an automatically selected subnet, subnet validation occurs in NewNetwork.
func WithDNSProxyDisabled ¶
func WithDNSProxyDisabled() NetworkConfigurationOption
WithDNSProxyDisabled requests that vmnet disable its DNS proxy. Configure guests to use another DNS resolver. This option does not filter DNS traffic or guarantee that queries to the host receive no response.
func WithExternalInterface ¶
func WithExternalInterface(name string) NetworkConfigurationOption
WithExternalInterface selects the host interface used to reach external networks, such as "en0". It requires ModeShared. If omitted, vmnet selects the external interface automatically. Empty names and names containing NUL are rejected; vmnet checks whether the interface can be used.
func WithIPv4Subnet ¶
func WithIPv4Subnet(prefix netip.Prefix) NetworkConfigurationOption
WithIPv4Subnet sets the network's IPv4 subnet. Host bits are ignored. Prefixes longer than /30 are rejected. The network, host (second), and broadcast addresses are reserved. DHCP reservations are checked against the final subnet after all options have been applied.
func WithIPv6Prefix ¶
func WithIPv6Prefix(prefix netip.Prefix) NetworkConfigurationOption
WithIPv6Prefix sets the network's IPv6 prefix. Host bits are ignored. IPv4-mapped IPv6 prefixes are rejected. The prefix ::/0 selects an automatic IPv6 prefix.
func WithMTU ¶
func WithMTU(mtu int) NetworkConfigurationOption
WithMTU sets the network's maximum transmission unit in bytes. NewNetworkConfiguration rejects values outside 1280 through 65535 before calling vmnet. The lower bound preserves the IPv6 minimum MTU; the upper bound prevents exceeding the Darwin interface limit. A value within this range may still be rejected by vmnet. If omitted, vmnet chooses the MTU.
func WithNAT44Disabled ¶
func WithNAT44Disabled() NetworkConfigurationOption
WithNAT44Disabled disables IPv4 network address translation. Guests need another route for external IPv4 traffic.
func WithNAT66Disabled ¶
func WithNAT66Disabled() NetworkConfigurationOption
WithNAT66Disabled disables IPv6 network address translation. Guests need another route for external IPv6 traffic.
func WithPortForwarding ¶
func WithPortForwarding(network string, externalPort uint16, destination netip.AddrPort) NetworkConfigurationOption
WithPortForwarding forwards a host port to a guest address and port. Network must be "tcp" or "udp". The destination determines the IP family. Both ports must be nonzero. Unspecified, multicast, IPv4-mapped IPv6, and zoned addresses are rejected.
Rules accumulate. For the same network, IP family, and external port, the last destination wins. Keep the guest address stable with WithDHCPReservation or static guest configuration. vmnet does not provide a host bind address; forwarded ports are not restricted to loopback.
func WithRouterAdvertisementDisabled ¶
func WithRouterAdvertisementDisabled() NetworkConfigurationOption
WithRouterAdvertisementDisabled disables IPv6 router advertisements. Guests need static IPv6 addresses and routes or another advertising router.
type NetworkSerialization ¶
type NetworkSerialization struct {
// contains filtered or unexported fields
}
NetworkSerialization is an opaque XPC representation of a logical network. It has no portable byte encoding. Its zero value is not usable.
type NetworkService ¶
type NetworkService struct {
// contains filtered or unexported fields
}
NetworkService publishes one logical network through a launchd Mach service. Clients obtain a reference with ReceiveNetwork, allowing virtual machines in separate processes to use the same network. XPC transfers the network reference; VM packets flow through vmnet.
The service retains the source network until NetworkService.Close. Keep the service open and its process running while clients use the network. A received reference does not preserve the source network reservation after the server releases it. Call Close when clients no longer need the network.
func ShareNetwork ¶
func ShareNetwork(name string, network *Network, peerRequirement string) (*NetworkService, error)
ShareNetwork publishes network through the launchd Mach service named name. It returns after creating the service and handles client requests internally. Clients use ReceiveNetwork to obtain a reference to the same logical network.
The caller must register name in the MachServices dictionary of the process's launchd property list and load the job with launchctl. ShareNetwork does not register the name. XPC may report connection or registration failures asynchronously, so successful creation does not confirm that clients can reach the service.
peerRequirement is an Apple code signing requirement expression checked against each client executable. It must be nonempty. The expression "true" accepts any executable and should not be used to expose a private network.
The returned service retains network. Keep the service open and this process running while clients use the network, then call NetworkService.Close.
ShareNetwork requires macOS 26 and newer.
func (*NetworkService) Close ¶
func (s *NetworkService) Close() error
Close stops accepting peers, closes existing XPC connections, and releases the service's reference to the source network. Call it only when clients no longer need the shared network; their references do not retain the source network reservation.
Repeated and concurrent calls have no additional effect.