swiftcocoaasyncsocket

GCDAsyncUDPSocket get source address from structure using swift


I am using CocoaAsyncSocket to send and receive UDP packets. My code is working but I'm not sure how to get the address of the sender. The following function receives the packet and has a variable address but it's passed as Data.

func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?)
{

}

I found in this post that the data is in the following structure format.

struct sockaddr_in {
__uint8_t   sin_len;
sa_family_t sin_family;
in_port_t   sin_port;
struct  in_addr sin_addr;
char        sin_zero[8];
};

In swift how would I go about changing the Data address to a structure and then getting the ip address from that?

Thanks!


Solution

  • I've managed to get information from the address with the following code taken from this other answer:

            var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
            do {
                try address.withUnsafeBytes { (pointer:UnsafePointer<sockaddr>) -> Void in
                    guard getnameinfo(pointer, socklen_t(address.count), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 else {
                        throw NSError(domain: "domain", code: 0, userInfo: ["error":"unable to get ip address"])
                    }
                }
            } catch {
                print(error)
                return
            }
            let senderAddress = String(cString:hostname)
    

    Hope it will help you