|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// Copyright © 2026 Apple Inc. and the Containerization project authors. |
| 3 | +// |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// |
| 8 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +// |
| 10 | +// Unless required by applicable law or agreed to in writing, software |
| 11 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +// See the License for the specific language governing permissions and |
| 14 | +// limitations under the License. |
| 15 | +//===----------------------------------------------------------------------===// |
| 16 | + |
| 17 | +#if os(macOS) |
| 18 | + |
| 19 | +import ContainerizationError |
| 20 | +import ContainerizationExtras |
| 21 | +import Virtualization |
| 22 | + |
| 23 | +/// A network interface that bridges the container onto a host physical interface. |
| 24 | +/// The IP address is assigned by the upstream DHCP server; `ipv4Address` is always nil. |
| 25 | +@available(macOS 26, *) |
| 26 | +public final class BridgedNetworkInterface: Interface, Sendable { |
| 27 | + public let hostInterfaceName: String |
| 28 | + public let macAddress: MACAddress? |
| 29 | + public let ipv4Address: CIDRv4? = nil |
| 30 | + public let ipv4Gateway: IPv4Address? = nil |
| 31 | + public let mtu: UInt32 = 1500 |
| 32 | + |
| 33 | + public init(hostInterfaceName: String, macAddress: MACAddress? = nil) { |
| 34 | + self.hostInterfaceName = hostInterfaceName |
| 35 | + self.macAddress = macAddress |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +@available(macOS 26, *) |
| 40 | +extension BridgedNetworkInterface: VZInterface { |
| 41 | + public func device() throws -> VZVirtioNetworkDeviceConfiguration { |
| 42 | + guard let vzIface = VZBridgedNetworkInterface.networkInterfaces |
| 43 | + .first(where: { $0.identifier == hostInterfaceName }) else { |
| 44 | + throw ContainerizationError( |
| 45 | + .invalidArgument, |
| 46 | + message: "no bridged interface named \(hostInterfaceName)") |
| 47 | + } |
| 48 | + let config = VZVirtioNetworkDeviceConfiguration() |
| 49 | + config.attachment = VZBridgedNetworkDeviceAttachment(interface: vzIface) |
| 50 | + if let mac = macAddress, let vzMac = VZMACAddress(string: mac.description) { |
| 51 | + config.macAddress = vzMac |
| 52 | + } |
| 53 | + return config |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +#endif |
0 commit comments