I need your help, this code does not compile anymore in Swift 3
//: Let's set up the `sockaddr_in` C structure using the initializer.
var sin = sockaddr_in(
sin_len: UInt8(sizeof(sockaddr_in)),
sin_family: sa_family_t(AF_INET),
sin_port: in_port_t(0),
sin_addr: in_addr(s_addr: inet_addr(routerIP)),
sin_zero: (0,0,0,0,0,0,0,0)
)
//: Now convert the structure into a `CFData` object.
let data = withUnsafePointer(&sin) { ptr in
CFDataCreate(kCFAllocatorDefault, UnsafePointer(ptr), sizeof(sockaddr_in))
}
//: Create the `CFHostRef` with the `CFData` object and store the retained value for later use.
host = CFHostCreateWithAddress(kCFAllocatorDefault, data).takeRetainedValue()
I have to fix the line "withUnsafePointer" but I don't know how?
I tried something like this
let data = withUnsafePointer(to: &sin) { ptr in
CFDataCreate(kCFAllocatorDefault, UnsafePointer(ptr), MemoryLayout<sockaddr_in>.size)
}
the compiler say I have to use withMemoryRebound but how ? thanks
NSData
has a convenient method to help you with this, and then you can take advantage of toll-free bridging to cast it to CFData
:
let data = NSData(bytes: &sin, length: MemoryLayout<sockaddr_in>.size) as CFData