You can simply use the appropriate C functions from the Darwin module. The part that is a bit complicated is casting from sockaddr_xyz structs to a generic sockaddr (maybe someone has a better solution than mine ...). Otherwise, it is pretty straight forward.
Updated for Swift 0.2 aka Xcode 6.3.1 (strlen () must be converted to Int).
Example:
let textToSend = "Hello World!"
func htons(value: CUnsignedShort) -> CUnsignedShort {
return (value << 8) + (value >> 8);
}
let INADDR_ANY = in_addr(s_addr: 0)
let fd = socket(AF_INET, SOCK_DGRAM, 0)
var addr = sockaddr_in(
sin_len: __uint8_t(sizeof(sockaddr_in)),
sin_family: sa_family_t(AF_INET),
sin_port: htons(1337),
sin_addr: INADDR_ANY,
sin_zero: ( 0, 0, 0, 0, 0, 0, 0, 0 )
)
textToSend.withCString { cstr -> Void in
withUnsafePointer(&addr) { ptr -> Void in
let addrptr = UnsafePointer<sockaddr>(ptr)
sendto(fd, cstr, Int(strlen(cstr)), 0,
addrptr, socklen_t(addr.sin_len))
}
}
source
share