vmnet

package
v4.0.0-...-0ec4d9e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 17 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Configure and share a network

These APIs require macOS 26 or later.

Configure a network

Pass functional options to NewNetworkConfiguration. The returned configuration is immutable and can be passed to NewNetwork:

config, err := vmnet.NewNetworkConfiguration(
    vmnet.ModeShared,
    vmnet.WithIPv4Subnet(netip.MustParsePrefix("192.168.120.0/24")),
    vmnet.WithIPv6Prefix(netip.MustParsePrefix("fd42:1234:120::/64")),
    vmnet.WithDHCPReservation(
        net.HardwareAddr{0x02, 0, 0, 0, 0, 1},
        netip.MustParseAddr("192.168.120.10"),
    ),
    vmnet.WithMTU(1500),
)
if err != nil {
    return err
}
network, err := vmnet.NewNetwork(config)
if err != nil {
    return err
}

Import net and net/netip for the address types in this example.

Options are validated before native configuration is created. The last IPv4 subnet, IPv6 prefix, or MTU wins. DHCP reservations accumulate by MAC address; repeating a MAC replaces its address. Invalid options return an error even if a later option would replace them.

Reservations are checked against the final IPv4 subnet, regardless of option order. When the subnet is selected automatically, NewNetwork checks reservations against the actual subnet. WithDHCPReservation copies the MAC address when the option is created, so options can be reused independently.

WithMTU accepts 1280 through 65535 bytes. This range enforces the IPv6 minimum and Darwin interface maximum; vmnet can still reject a value within the range.

Select an external interface

Use WithExternalInterface to select the host interface that a shared network uses to reach external networks:

config, err := vmnet.NewNetworkConfiguration(
    vmnet.ModeShared,
    vmnet.WithExternalInterface("en0"),
)
if err != nil {
    return err
}

This option requires ModeShared. Omit it to let vmnet select the interface automatically. Empty names and names containing NUL are rejected. vmnet checks whether the named interface can be used.

Disable network services

These options apply vmnet's service-disable settings. Omit an option to preserve vmnet's default for the selected mode. The options can be combined, repeated, and reused across configurations.

Option Effect
WithDHCPDisabled() Disables the DHCP server. Configure guest IPv4 addresses manually or provide another DHCP server.
WithDNSProxyDisabled() Requests that vmnet disable the DNS proxy. Configure guests to use another DNS resolver.
WithNAT44Disabled() Disables IPv4 NAT. External IPv4 traffic needs another route.
WithNAT66Disabled() Disables IPv6 NAT. External IPv6 traffic needs another route.
WithRouterAdvertisementDisabled() Disables IPv6 router advertisements. Configure guest IPv6 addresses and routes manually or provide another advertising router.

For example, to use static guest addresses without vmnet's DHCP server or IPv6 router advertisements:

config, err := vmnet.NewNetworkConfiguration(
	vmnet.ModeShared,
	vmnet.WithDHCPDisabled(),
	vmnet.WithRouterAdvertisementDisabled(),
)
if err != nil {
	return err
}

These options do not configure guest addresses, routes, or DNS resolvers. WithDNSProxyDisabled does not filter DNS traffic or guarantee that queries to the host receive no response.

Forward host ports to a guest

Use WithPortForwarding to forward TCP or UDP traffic to a guest. The address in the destination selects IPv4 or IPv6. Give the guest a stable address through a DHCP reservation or static guest configuration:

config, err := vmnet.NewNetworkConfiguration(
    vmnet.ModeShared,
    vmnet.WithIPv4Subnet(netip.MustParsePrefix("192.168.120.0/24")),
    vmnet.WithDHCPReservation(
        net.HardwareAddr{0x02, 0, 0, 0, 0, 1},
        netip.MustParseAddr("192.168.120.10"),
    ),
    vmnet.WithPortForwarding("tcp", 8080, netip.MustParseAddrPort("192.168.120.10:80")),
    vmnet.WithPortForwarding("udp", 5353, netip.MustParseAddrPort("192.168.120.10:53")),
)
if err != nil {
    return err
}
network, err := vmnet.NewNetwork(config)
if err != nil {
    return err
}

These rules take effect when the network starts. The destination service must be listening in the guest. Each rule uses "tcp" or "udp" and nonzero host and guest ports. Repeating the same protocol, IP family, and host port replaces the destination. Rules for different protocols or IP families remain separate.

Use WithExternalInterface to select the external interface for a shared network's forwarded traffic. For IPv6, that interface needs a reachable IPv6 address, and the guest needs a return route to the client.

vmnet does not offer a host bind address for these rules. A forwarded port is not limited to 127.0.0.1 or ::1; account for access from other hosts when choosing which guest services to expose.

Share a network between processes

CopySerialization returns an opaque XPC object. NewNetworkWithSerialization restores a network from that object. The serialization is not a byte encoding and cannot be written to a file.

Use ShareNetwork and ReceiveNetwork to share a network through a launchd Mach service.

flowchart LR
    subgraph A["Process A"]
        direction TB
        source["Source Network"]
        share["ShareNetwork"]
        vmA["VM A"]
        source --> share
        source -->|"Attach"| vmA
    end

    subgraph B["Process B"]
        direction TB
        receive["ReceiveNetwork"]
        imported["Received Network"]
        vmB["VM B"]
        receive --> imported
        imported -->|"Attach"| vmB
    end

    share -.->|"Network reference over XPC"| receive
    vmA <-->|"Packets through the same vmnet network"| vmB

XPC transfers the network reference. VM packets flow through the shared vmnet network. Keep the sharing service and its process running while clients use the network.

The server publishes one network:

service, err := vmnet.ShareNetwork("com.example.vmnetwork", network, clientRequirement)
if err != nil {
	return err
}
defer service.Close()

The client obtains its own network reference:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
network, err := vmnet.ReceiveNetwork(ctx, "com.example.vmnetwork", serverRequirement)
if err != nil {
	return err
}

Pass the received network to vz.NewVMNetNetworkDeviceAttachment or vmnet.StartInterfaceWithNetwork. Keep the service open and its process running while clients use the shared network. The service retains the source network until it closes. A received reference does not preserve the source network reservation after the server releases it.

Register the service name in the server's launchd property list:

<key>MachServices</key>
<dict>
    <key>com.example.vmnetwork</key>
    <true/>
</dict>

The property list also needs Label and ProgramArguments. Load a user agent with launchctl bootstrap gui/$(id -u) /path/to/service.plist and remove it with launchctl bootout gui/$(id -u)/com.example.vmnetwork, using its label in the second command. ShareNetwork does not register the name with launchd. Connection and registration failures can be reported asynchronously by XPC. Use a deadline when receiving a network.

Both functions require an Apple code signing requirement expression for the remote executable. For binaries signed with a Developer ID certificate, a requirement can combine the signing identifier and team identifier:

anchor apple generic and identifier "com.example.vmhost" and certificate leaf[subject.OU] = "TEAMID1234"

For development with one ad hoc signed executable, use cdhash H"..." with the hash printed by codesign -d -vvvv /path/to/executable. Rebuilding or signing the executable changes its hash. The server checks clients and each client checks the server. An empty requirement is rejected. A requirement of true accepts any executable and should not be used for a service that exposes a private network.

Documentation

Overview

Package vmnet configures logical networks provided by Apple's vmnet framework.

Index

Examples

Constants

This section is empty.

Variables

View Source
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

func BridgedInterfaces() ([]string, error)

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 Error

type Error = objcutil.NSError

Error contains the details of an error returned by vmnet.framework.

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

func (i *Interface) MTU() int

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

func (i *Interface) MaxPacketSize() int

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

func (i *Interface) ReadPacket(ctx context.Context, frame []byte) (int, error)

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

func (i *Interface) ReadPackets(ctx context.Context, frames [][]byte) (int, error)

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.
	}
}

func (*Interface) Stop

func (i *Interface) Stop() error

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

func (i *Interface) TSOEnabled() bool

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

func (i *Interface) VirtioHeaderEnabled() bool

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

func (i *Interface) WritePacket(frame []byte) error

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

func (i *Interface) WritePackets(frames [][]byte) (int, error)

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
	}
}

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.

See: https://developer.apple.com/documentation/vmnet/vmnet_enable_virtio_header_key-swift.var?language=objc

type Mode

type Mode int

Mode specifies how a vmnet network connects its virtual machines.

const (
	// ModeHost connects virtual machines to each other and to the host.
	ModeHost Mode = 1000
	// ModeShared also connects virtual machines to outside networks using NAT.
	ModeShared Mode = 1001
)

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

func ReceiveNetwork(ctx context.Context, name, peerRequirement string) (*Network, error)

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

func (n *Network) IPv4Subnet() (netip.Prefix, error)

IPv4Subnet returns the reserved IPv4 subnet, including an automatically selected subnet when none was configured. It requires macOS 26 and newer.

func (*Network) IPv6Prefix

func (n *Network) IPv6Prefix() (netip.Prefix, error)

IPv6Prefix returns the reserved IPv6 prefix, including an automatically selected prefix 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL