1

I saw the question here : cast-sockaddr-in-to-sockaddr-in-swift 1.2

But when I try to use these code in swift 2.0, I got an error:

var sa = sockaddr_in()
let s =  socket(PF_INET,SOCK_STREAM,0)

let cn = connect(s,UnsafeMutablePointer( &sa ), sizeof(sa) )

Ambiguous use of 'init'

How to fix this problem?

Community
  • 1
  • 1
wj2061
  • 6,778
  • 3
  • 36
  • 62

1 Answers1

9

Similarly as in the referenced Q&A, you have to use withUnsafePointer()

var sa = sockaddr_in()
let s =  socket(PF_INET,SOCK_STREAM,0)

let cn = withUnsafePointer(&sa) { 
    connect(s, UnsafePointer($0), socklen_t(sizeofValue(sa)))
}

Note also that sizeofValue() must be used with an instance of a type, and that the value must be converted to socklen_t as expected by connect().

Update for Swift 3:

let cn = withUnsafeMutablePointer(to: &sa) {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
        connect(s, $0, socklen_t(MemoryLayout.size(ofValue: sa)))
    }
}
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Except that gives "Cannot convert value of type 'inout sockaddr_in' to expected argument type 'inout _'". So, no. – Honza Jan 14 '17 at 17:48
  • @Honza: The question and answer referred to Swift 2. Pointer conversion changed considerably with Swift 3. I have added the corresponding Swift 3 code. – Martin R Jan 14 '17 at 18:12