如何快速将sockadd转换为sockaddr

如何快速将sockadd转换为sockaddr

本文介绍了如何快速将sockadd转换为sockaddr_in的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var sa_tab:[sockaddr?] = [sockaddr](repeating: sockaddr(), count: Int(RTAX_MAX))
let addr:sockaddr = sa_tab[Int(RTAX_DST)]!
let addr_in:sockaddr_in = unsafeBitCast(addr.self, to: UnsafeMutablePointer<sockaddr_in>.self).pointee

m在第三行崩溃,在不同大小的类型之间不能unsafeBitCast

这是完整的方法。 / p>

Here is the complete method.

func ROUNDUP(a:Int) -> Int{
    if (a) > 0 {
        return (1 + (((a) - 1) | (MemoryLayout<CLong>.size - 1)))
    }
    else{

    return MemoryLayout<CLong>.size
    }
}

class func defaultGatewayAddress() -> Int{

        var addressIntValue:UInt32 = 0
        var mib:[Int32] = [CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY]
        let l = UnsafeMutablePointer<Int>.allocate(capacity: MemoryLayout<Int>.size)
        var buf: UnsafeMutablePointer<CChar>?
        var p: UnsafeMutablePointer<CChar>?
        var rt: UnsafeMutablePointer<rt_msghdr>?
        var sa:UnsafeMutablePointer<sockaddr>?
        var sa_tab:[sockaddr?] = [sockaddr](repeating: sockaddr(), count: Int(RTAX_MAX))
        var _:Int
        var r:Int = -1

        if(sysctl(&mib, u_int(mib.count), nil, l, nil, 0) < 0) {
            return -1;
        }
        print(Int8.max)
        print(Int8.min)
        if(l.pointee > 0) {

            buf = UnsafeMutablePointer<CChar>.allocate(capacity: l.pointee)

            if(sysctl(&mib, u_int(mib.count), buf, l, nil, 0) < 0) {
                return -1;
            }


            p = buf
            let maxBuf = buf!.advanced(by: l.pointee)

            while (p! < maxBuf) {

                rt = p!.withMemoryRebound(to: rt_msghdr.self, capacity: 1, {$0})
                sa = rt!.advanced(by: 1).withMemoryRebound(to: sockaddr.self, capacity: 1, {$0})

                for i in 0..<RTAX_MAX {
                    if (rt!.pointee.rtm_addrs & (1 << i)) == 1{
                        print("insert \(sa!.pointee) at \(i)")
                        sa_tab.insert(sa!.pointee, at: Int(i))
                        sa = sa!.advanced(by: ROUNDUP(a: Int(sa!.pointee.sa_len)))
                    }
                    else{
                        sa_tab.insert(nil, at: Int(i))
                    }
                    if ((rt!.pointee.rtm_addrs & (RTA_DST|RTA_GATEWAY)) ==  (RTA_DST|RTA_GATEWAY)) &&
                        (sa_tab[Int(RTAX_DST)]?.sa_family == sa_family_t(AF_INET)) &&
                        (sa_tab[Int(RTAX_GATEWAY)]?.sa_family == sa_family_t(AF_INET)){

                        var addr:sockaddr = sa_tab[Int(RTAX_DST)]!

                        let addr_in:sockaddr_in = withUnsafePointer(to: &addr) {
                            $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
                                $0.pointee
                            }
                        }

                        if addr_in.sin_addr.s_addr == 0 {
                            var buffer = [CChar](repeating: CChar(0), count: Int(IFNAMSIZ) + 1)
                            let result = if_indextoname(UInt32((rt?.pointee.rtm_index)!), &buffer)
                            var char = "en0".cString(using: .utf8)
                            #if arch(i386) || arch(x86_64)
                                // This is a Simulator not an idevice
                                char = "en1".cString(using: .utf8)
                            #endif

                            if(strcmp(result, char) == 0){
                                r = 0
                                var gatewayAddr:sockaddr = sa_tab[Int(RTAX_GATEWAY)]!

                                let gatewayAddr_in:sockaddr_in = withUnsafePointer(to: &gatewayAddr) {
                                    $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
                                        $0.pointee
                                    }
                                }
                                addressIntValue = gatewayAddr_in.sin_addr.s_addr
                            }
                        }


                    }
                }

                p = p?.advanced(by: Int((rt?.pointee.rtm_msglen)!))

            }

            buf!.deallocate(capacity: l.pointee)

            let gatewayLongAddress:UInt32 = addressIntValue

            print("gatewayLongAddress: \(gatewayLongAddress)")

            let gatewayIPAddress = String(format:"%d.%d.%d.%d", (gatewayLongAddress & 0xFF),
                                          ((gatewayLongAddress >> 8) & 0xFF),
                                          ((gatewayLongAddress >> 16) & 0xFF),
                                          ((gatewayLongAddress >> 24) & 0xFF))

            print("gatewayIPAddress: \(gatewayIPAddress)")

        }

        return Int(addressIntValue)
    }


推荐答案

您必须输入 addr 地址 $ c>(要求
addr 变量),使用 withMemoryRebound()
暂时将其重新绑定到 sockaddr_in 指针,然后可以将
取消引用:

You have to take the address of addr (which requiresaddr to be a variable), use withMemoryRebound() totemporarily rebind it to an sockaddr_in pointer, which can thenbe dereferenced:

var addr: sockaddr = ...
let addr_in = withUnsafePointer(to: &addr) {
    $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
        $0.pointee
    }
}






您的 defaultGatewayAddress( )方法:


  • sa = sa!.advanced(作者:ROUNDUP(a :Int(sa!.pointee.sa_len)))使 sa 前进
    sa_len 乘以 sockaddr 的大小,这不是您想要的。

  • 测试 if (((rt!.pointee.rtm_addrs& (RTA_DST | RTA_GATEWAY))==(RTA_DST | RTA_GATEWAY))
    必须在之后在0中为i的之后完成。 ; RTAX_MAX 循环。

  • 带有 sa_tab.insert(sa!.pointee,at:Int(i))插入新元素到
    数组中,而不是替换它们。

  • sa = sa!.advanced(by: ROUNDUP(a: Int(sa!.pointee.sa_len))) advances sa bysa_len multiplied with the size of sockaddr, which is not what you intend.
  • The test if ((rt!.pointee.rtm_addrs & (RTA_DST|RTA_GATEWAY)) == (RTA_DST|RTA_GATEWAY))must be done after the for i in 0..<RTAX_MAX loop.
  • With sa_tab.insert(sa!.pointee, at: Int(i)) you insert new elements into thearray instead of replacing them.

还请注意

rt = p!.withMemoryRebound(to: rt_msghdr.self, capacity: 1, {$0})

可以在这里工作,但是通常不安全: $ 0 指针仅对执行关闭操作的
有效,并且不得传递给外部。

might work here, but it generally unsafe: The $0 pointer is only valid forthe execution of the closure and must not be passed to the outside.

这是您的代码的有效版本。它实质上是
的翻译
到Swift(反过来,它似乎建立在)。

Here is a working version of your code. It is essentially a translation ofHow can I determine the default gateway on iPhone?to Swift (which in turn seems it built on https://github.com/getlantern/libnatpmp/blob/master/getgateway.c).

我也对其进行了一些简化,并进行了修改,以避免所有强制拆包。

I have also simplified it a bit and modified to avoid all forced unwraps.

func defaultGatewayAddress() -> in_addr? {

    var defaultGateway: in_addr?

    var mib:[Int32] = [CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY]
    var len = 0
    if sysctl(&mib, u_int(mib.count), nil, &len, nil, 0) < 0 {
        return nil
    }
    let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: len)
    defer {
        buffer.deallocate(capacity: len)
    }
    if sysctl(&mib, u_int(mib.count), buffer, &len, nil, 0) < 0 {
        return nil
    }

    var sa_tab = [UnsafePointer<sockaddr>?](repeating: nil, count: Int(RTAX_MAX))

    var ptr = buffer
    while ptr < buffer + len {
        ptr.withMemoryRebound(to: rt_msghdr.self, capacity: 1) { rt in
            var sa = UnsafeMutableRawPointer(rt + 1).assumingMemoryBound(to: sockaddr.self)
            for i in 0..<RTAX_MAX {
                if rt.pointee.rtm_addrs & (1 << i) != 0 {
                    sa_tab[Int(i)] = UnsafePointer(sa)
                    sa = (UnsafeMutableRawPointer(sa) + Int(sa.pointee.sa_len)).assumingMemoryBound(to: sockaddr.self)
                } else {
                     sa_tab[Int(i)] =  nil
                }
            }

            if let dst = sa_tab[Int(RTAX_DST)],
                dst.pointee.sa_family == sa_family_t(AF_INET),
                let gateway = sa_tab[Int(RTAX_GATEWAY)],
                gateway.pointee.sa_family == sa_family_t(AF_INET)
            {
                dst.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { addr in
                    if addr.pointee.sin_addr.s_addr == 0 {

                        var name = [CChar](repeating: CChar(0), count: Int(IFNAMSIZ) + 1)
                        if_indextoname(UInt32((rt.pointee.rtm_index)), &name)
                        if String(cString: name) == "en0" {
                            defaultGateway = gateway.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
                                $0.pointee.sin_addr
                            }
                        }
                    }
                }

            }
            ptr += Int(rt.pointee.rtm_msglen)
        }
    }

    return defaultGateway
}

这篇关于如何快速将sockadd转换为sockaddr_in的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 17:11