This looks like a dupe to Swift UDP Connection.
Refactoring the example a little bit:
let INADDR_ANY = in_addr(s_addr: 0)
udpSend("Hello World!", address: INADDR_ANY, port: 1337)
func udpSend(textToSend: String, address: in_addr, port: CUnsignedShort) {
func htons(value: CUnsignedShort) -> CUnsignedShort {
return (value << 8) + (value >> 8);
}
let fd = socket(AF_INET, SOCK_DGRAM, 0) // DGRAM makes it UDP
var addr = sockaddr_in(
sin_len: __uint8_t(sizeof(sockaddr_in)),
sin_family: sa_family_t(AF_INET),
sin_port: htons(port),
sin_addr: address,
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, strlen(cstr), 0, addrptr, socklen_t(addr.sin_len))
}
}
close(fd)
}
If you have the target IP as a string, use inet_pton() to convert it to an in_addr. Like so:
var addr = in_addr()
inet_pton(AF_INET, "192.168.0.1", &buf)
Feel free to steal code from over here: SwiftSockets
Oh, and if you plan to do any serious network programming, grab this book: Unix Network Programming