Skip to content

How get a socket port number in swift and interact with the native socket api

Brice edited this page Feb 20, 2021 · 1 revision

To figure a free port and use the c api, you need to create a sockaddr_in structure in swift

        // Create the c structure and get the size with MemoryLayout
        var addr = sockaddr_in()
        var size : socklen_t = socklen_t(MemoryLayout<sockaddr_in>.size)
        
        addr.sin_family = sa_family_t(AF_INET)
        addr.sin_addr = in_addr(s_addr: INADDR_ANY)
        addr.sin_port = 0

You then will need to typecast it to replicate the equivalent c code:

        sockaddr_in * addr
        bind( (sockaddr*)&addr, ... )

The way it can be done in swift if to first create a Data object and then convert it to the appropriate buffer:

        // First convert the structure memory to Data
        var data = Data(bytes: &addr, count: Int(size))
        // Then create a memory buffer with the Data object
        data.withUnsafeMutableBytes { (pointer: UnsafeMutableRawBufferPointer) -> Void in
            // finally cast the pointer to the buffer as a sockaddr
            let ptr = pointer.bindMemory(to: sockaddr.self)
            // Pass the sockaddr pointer to bind (the point actually points to a sockaddr_in)
            let bindrv = bind(sockfd, ptr.baseAddress, size)