2

我还没有找到如何将以下行(错误)调整为 Swift 4 的解决方案。关于文档,应该使用 withUnsafePointer 方法,但我找不到将 addressBytes.bytes 添加到代码中的方法。

在此处输入图像描述

func netServiceDidResolveAddress(_ sender: NetService) {
    //service.addresses - array containing NSData objects, each of which contains an appropriate
    //sockaddr structure that you can use to connect to the socket
    for addressBytes in sender.addresses!
    {
        var inetAddress : sockaddr_in!
        var inetAddress6 : sockaddr_in6?
        //NSData’s bytes returns a read-only pointer (const void *) to the receiver’s contents.
        //var bytes: UnsafePointer<()> { get }
        let inetAddressPointer = UnsafePointer<sockaddr_in>(addressBytes.bytes)
        //Access the underlying raw memory
        inetAddress = inetAddressPointer.memory

        if inetAddress.sin_family == __uint8_t(AF_INET) //Note: explicit convertion (var AF_INET: Int32 { get } /* internetwork: UDP, TCP, etc. */)
        {
        }
        else
        {
            if inetAddress.sin_family == __uint8_t(AF_INET6) //var AF_INET6: Int32 { get } /* IPv6 */
            {
                let inetAddressPointer6 = UnsafePointer<sockaddr_in6>(addressBytes.bytes)
                inetAddress6 = inetAddressPointer6.memory
                inetAddress = nil
            }
            else
            {
                inetAddress = nil
            }
        }
        var ipString : UnsafePointer<Int8>?
        //static func alloc(num: Int) -> UnsafeMutablePointer<T>
        let ipStringBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: Int(INET6_ADDRSTRLEN))
            if (inetAddress != nil)
        {
4

1 回答 1

-2

已编辑

这是在 sockaddr 上的 Xcode 10 中使用带有 swift 4.2 的“withUnsafePointer”的示例。我实际上使用了两个嵌套的“withUnsafePointer”闭包,因为我需要两个不安全的指针。

我必须将“快速编译器 -> 代码生成 -> 对内存的独占访问”设置为“不强制执行”才能使其正常工作。

请注意,使用 sendto() 发送原始数据包需要以 root 身份运行程序(例如 sudo)

let sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)

// I have a custom sockaddr extension which fully initializes my sockaddr
guard var socka = sockaddr(ipv4string: "1.1.1.1", port: 0) else { fatalError() }

// I have a custom struct that generates my icmp packet and calculates the checksum
var mypacket = IcmpEchoRequest()

let result2 = withUnsafePointer(to: &mypacket) { mypacketPointer in
    let result = withUnsafePointer(to: &socka) { sockaPointer in
        let sendResult = sendto(sockfd, mypacketPointer, mypacket.length, 0, sockaPointer, socklen_t(MemoryLayout<sockaddr>.size))
        print("sendResult \(sendResult)")
    }
}
于 2018-10-04T23:32:40.903 回答