如何在swift 2.0中将sockaddr_in转换为sockaddr?

时间:2015-12-01 08:09:42

标签: swift sockets

我在这里看到了这个问题: cast-sockaddr-in-to-sockaddr-in-swift 1.2

但是当我尝试在swift 2.0中使用这些代码时,我收到了一个错误:

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

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

模糊地使用'init'

如何解决这个问题?

1 个答案:

答案 0 :(得分:7)

referenced Q&A类似,您必须使用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)))
}

另请注意,sizeofValue()必须与实例一起使用 一个类型,并且该值必须转换为socklen_t 正如预期connect()

Swift 3的更新:

let cn = withUnsafeMutablePointer(to: &sa) {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
        connect(s, $0, socklen_t(MemoryLayout.size(ofValue: sa)))
    }
}