Sunrise17
Sunrise17

Reputation: 389

Unsafepointer adjustment for Swift 4

I have not found a solution how i can adjust the following lines (error) to Swift 4. Regarding to documents, withUnsafePointer method should be used but i could not find a way to add addressBytes.bytes into code.

enter image description here

func netServiceDidResolveAddress(_ sender: NetService) {
    //service.addresses - array containing NSData objects, each of which contains an appropriate
    //sockaddr structure that you can use to connect to the socket
    for addressBytes in sender.addresses!
    {
        var inetAddress : sockaddr_in!
        var inetAddress6 : sockaddr_in6?
        //NSData’s bytes returns a read-only pointer (const void *) to the receiver’s contents.
        //var bytes: UnsafePointer<()> { get }
        let inetAddressPointer = UnsafePointer<sockaddr_in>(addressBytes.bytes)
        //Access the underlying raw memory
        inetAddress = inetAddressPointer.memory

        if inetAddress.sin_family == __uint8_t(AF_INET) //Note: explicit convertion (var AF_INET: Int32 { get } /* internetwork: UDP, TCP, etc. */)
        {
        }
        else
        {
            if inetAddress.sin_family == __uint8_t(AF_INET6) //var AF_INET6: Int32 { get } /* IPv6 */
            {
                let inetAddressPointer6 = UnsafePointer<sockaddr_in6>(addressBytes.bytes)
                inetAddress6 = inetAddressPointer6.memory
                inetAddress = nil
            }
            else
            {
                inetAddress = nil
            }
        }
        var ipString : UnsafePointer<Int8>?
        //static func alloc(num: Int) -> UnsafeMutablePointer<T>
        let ipStringBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: Int(INET6_ADDRSTRLEN))
            if (inetAddress != nil)
        {

Upvotes: 2

Views: 1360

Answers (1)

Darrell Root
Darrell Root

Reputation: 844

EDITED

Here's an example of using "withUnsafePointer" with swift 4.2 in Xcode 10 on a sockaddr. I actually use two nested "withUnsafePointer" closures because I need two unsafe pointers.

I had to set "swift compiler -> code generation -> exclusive access to memory" to "no enforcement" to get this to work.

Note that using sendto() to send raw packets requires running the program as root (sudo for example)

let sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)

// I have a custom sockaddr extension which fully initializes my sockaddr
guard var socka = sockaddr(ipv4string: "1.1.1.1", port: 0) else { fatalError() }

// I have a custom struct that generates my icmp packet and calculates the checksum
var mypacket = IcmpEchoRequest()

let result2 = withUnsafePointer(to: &mypacket) { mypacketPointer in
    let result = withUnsafePointer(to: &socka) { sockaPointer in
        let sendResult = sendto(sockfd, mypacketPointer, mypacket.length, 0, sockaPointer, socklen_t(MemoryLayout<sockaddr>.size))
        print("sendResult \(sendResult)")
    }
}

Upvotes: -2

Related Questions