Skip to content

Commit

Permalink
API for add/drop multicast membership
Browse files Browse the repository at this point in the history
  • Loading branch information
lhoward committed Aug 2, 2024
1 parent 4c44bf5 commit e49d89d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
11 changes: 10 additions & 1 deletion Sources/IORingUtils/Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public extension IORing {
}
}

extension UnsafeMutablePointer {
extension UnsafePointer {
func propertyBasePointer<Property>(to property: KeyPath<Pointee, Property>)
-> UnsafePointer<Property>?
{
Expand All @@ -89,6 +89,15 @@ extension UnsafeMutablePointer {
}
}

extension UnsafeMutablePointer {
func propertyBasePointer<Property>(to property: KeyPath<Pointee, Property>)
-> UnsafeMutablePointer<Property>?
{
guard let offset = MemoryLayout<Pointee>.offset(of: property) else { return nil }
return (UnsafeMutableRawPointer(self) + offset).assumingMemoryBound(to: Property.self)
}
}

extension IORing {
func connect(_ fd: FileDescriptorRepresentable, to address: any SocketAddress) async throws {
var addressBuffer = [UInt8]()
Expand Down
37 changes: 37 additions & 0 deletions Sources/IORingUtils/Socket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,43 @@ public struct Socket: CustomStringConvertible, Equatable, Hashable, Sendable {
try setBooleanOption(level: CInt(IPPROTO_TCP), option: TCP_NODELAY, to: true)
}

private func _addOrDropMembership(
_ add: Bool,
address: sockaddr_ll,
on interfaceIndex: Int
) throws {
guard let fileHandle else { throw Errno.badFileDescriptor }
var address = address
var mreq = packet_mreq()
mreq.mr_ifindex = Int32(interfaceIndex)
mreq.mr_type = UInt16(PACKET_MR_MULTICAST)
mreq.mr_alen = UInt16(address.sll_halen)
withUnsafeMutablePointer(to: &mreq.mr_address) { dstAddress in
withUnsafePointer(to: &address.sll_addr) { srcAddress in
let dstAddressPtr = dstAddress.propertyBasePointer(to: \.0)!
let srcAddressPtr = srcAddress.propertyBasePointer(to: \.0)!
memcpy(dstAddressPtr, srcAddressPtr, Int(address.sll_halen))
}
}
try Errno.throwingGlobalErrno {
setsockopt(
fileHandle.fileDescriptor,
SOL_PACKET,
add ? PACKET_ADD_MEMBERSHIP : PACKET_DROP_MEMBERSHIP,
&mreq,
socklen_t(MemoryLayout<packet_mreq>.size)
)
}
}

public func addMulticastMembership(for address: sockaddr_ll, on interfaceIndex: Int) throws {
try _addOrDropMembership(true, address: address, on: interfaceIndex)
}

public func dropMulticastMembership(for address: sockaddr_ll, on interfaceIndex: Int) throws {
try _addOrDropMembership(false, address: address, on: interfaceIndex)
}

public func bind(port: UInt16) throws {
switch Int32(domain) {
case AF_INET:
Expand Down

0 comments on commit e49d89d

Please sign in to comment.