Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UDP Connection

Tags:

swift

udp

I am new to Swift and have some questions about UDP connections.

Could someone provide a link or some short lines of code showing how I can connect a Swift client to a Java server?

like image 694
user3838885 Avatar asked Nov 07 '25 07:11

user3838885


1 Answers

You can just use the relevant C functions, from the 'Darwin' module. The part which is a bit tricky is the casting from sockaddr_xyz structs to the 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).

Sample:

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) // 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(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))
  }
}
like image 121
hnh Avatar answered Nov 09 '25 10:11

hnh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!