create a udp server in swift

To create a UDP server in Swift, we can use socket programming with GCD. Here's the code:

main.swift
import Foundation

// create socket
var socketFileDescriptor: Int32 = -1
socketFileDescriptor = socket(AF_INET, SOCK_DGRAM, 0)

if socketFileDescriptor == -1 {
    print("Error: Could not create socket.")
    exit(0)
}

// set up address and port
var address = sockaddr_in()
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
address.sin_port = in_port_t(12345)
address.sin_addr.s_addr = INADDR_ANY

// bind socket
let bindResult = withUnsafePointer(to: &address) {
    bind(socketFileDescriptor, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size))
}
if bindResult == -1 {
    print("Error: Could not bind socket.")
    exit(0)
}

// receive data
let bufferSize = 1024
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
while true {
    let result = recvfrom(socketFileDescriptor, buffer, bufferSize, 0, nil, nil)

    if result > 0 {
        let data = Data(bytes: buffer, count: result)
        let message = String(data: data, encoding: .utf8)
        print("Received message: \(message ?? "")")
    }
}

// close socket
close(socketFileDescriptor)
1155 chars
43 lines

This code creates a socket with socket(AF_INET, SOCK_DGRAM, 0), sets up an address and port with sockaddr_in, binds the socket to the address and port with bind(), receives data with recvfrom(), and prints out the received message. The server listens on port 12345, but you can change the port to any available port you wish to use.

Note the use of UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) for buffer allocation, and Data(bytes: buffer, count: result) to convert the received bytes to Data. Also, remember to close the socket with close(socketFileDescriptor) when you're done.

gistlibby LogSnag