如何在 Swift iOS 中获取路由器的 IP 地址

Posted

技术标签:

【中文标题】如何在 Swift iOS 中获取路由器的 IP 地址【英文标题】:How to get the IP Address of Router in Swift iOS 【发布时间】:2021-08-14 19:37:23 【问题描述】:

我想从我的 iPhone 获取所连接路由器的 IP 地址。我只获取我的 iPhone 的 IP 地址。

有什么方法可以获取主机/路由器的IP地址吗?

顺便说一句,我已经查看了以下链接,但那里没有解决方案:

    How to get Ip address in swift How do I get the IP address of a local hostname in local network in Swift Swift - Get device's WIFI IP Address

我正在尝试在 Swift 5 中使用 XCode 12.4 来实现

【问题讨论】:

你需要调用外部api获取公共和路由器ip @Anbu.Karthik,你能解释一下我应该调用哪个外部 API 吗?我需要单独创建它们吗? 你应该检查***.com/questions/58503680/… 【参考方案1】:

您可以使用 sysctl 从路由表中获取默认网关的 IP 地址,但首先您应该定义所需的结构和常量,因为 Darwin.net.route<route.h> 不会暴露给 ios SDK:

let RTAX_GATEWAY = 1
let RTAX_MAX = 8

public struct rt_metrics 
    public var rmx_locks: UInt32 /* Kernel leaves these values alone */
    public var rmx_mtu: UInt32 /* MTU for this path */
    public var rmx_hopcount: UInt32 /* max hops expected */
    public var rmx_expire: Int32 /* lifetime for route, e.g. redirect */
    public var rmx_recvpipe: UInt32 /* inbound delay-bandwidth product */
    public var rmx_sendpipe: UInt32 /* outbound delay-bandwidth product */
    public var rmx_ssthresh: UInt32 /* outbound gateway buffer limit */
    public var rmx_rtt: UInt32 /* estimated round trip time */
    public var rmx_rttvar: UInt32 /* estimated rtt variance */
    public var rmx_pksent: UInt32 /* packets sent using this route */
    public var rmx_state: UInt32 /* route state */
    public var rmx_filler: (UInt32, UInt32, UInt32) /* will be used for TCP's peer-MSS cache */


public struct rt_msghdr2 
    public var rtm_msglen: u_short /* to skip over non-understood messages */
    public var rtm_version: u_char /* future binary compatibility */
    public var rtm_type: u_char /* message type */
    public var rtm_index: u_short /* index for associated ifp */
    public var rtm_flags: Int32 /* flags, incl. kern & message, e.g. DONE */
    public var rtm_addrs: Int32 /* bitmask identifying sockaddrs in msg */
    public var rtm_refcnt: Int32 /* reference count */
    public var rtm_parentflags: Int32 /* flags of the parent route */
    public var rtm_reserved: Int32 /* reserved field set to 0 */
    public var rtm_use: Int32 /* from rtentry */
    public var rtm_inits: UInt32 /* which metrics we are initializing */
    public var rtm_rmx: rt_metrics /* metrics themselves */


public func getDefaultGateway() -> String? 
    var name: [Int32] = [
        CTL_NET,
        PF_ROUTE,
        0,
        0,
        NET_RT_DUMP2,
        0
    ]
    let nameSize = u_int(name.count)
    
    var bufferSize = 0
    sysctl(&name, nameSize, nil, &bufferSize, nil, 0)
    
    let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
    defer  buffer.deallocate() 
    buffer.initialize(repeating: 0, count: bufferSize)
    
    guard sysctl(&name, nameSize, buffer, &bufferSize, nil, 0) == 0 else  return nil 
    
    // Routes
    var rt = buffer
    let end = rt.advanced(by: bufferSize)
    while rt < end 
        let msg = rt.withMemoryRebound(to: rt_msghdr2.self, capacity: 1)  $0.pointee 
        
        // Addresses
        var addr = rt.advanced(by: MemoryLayout<rt_msghdr2>.stride)
        for i in 0..<RTAX_MAX 
            if (msg.rtm_addrs & (1 << i)) != 0 && i == RTAX_GATEWAY 
                let si = addr.withMemoryRebound(to: sockaddr_in.self, capacity: 1)  $0.pointee 
                if si.sin_addr.s_addr == INADDR_ANY 
                    return "default"
                
                else 
                    return String(cString: inet_ntoa(si.sin_addr), encoding: .ascii)
                
            
            
            let sa = addr.withMemoryRebound(to: sockaddr.self, capacity: 1)  $0.pointee 
            addr = addr.advanced(by: Int(sa.sa_len))
        
        
        rt = rt.advanced(by: Int(msg.rtm_msglen))
    
    
    return nil


// How to use
if let ip = getDefaultGateway() 
    print(ip)

// Prints: 192.168.1.1


【讨论】:

如果网关是0.0.0.0,我们能否在iOS中获取连接的Access Point的IP地址? 我们尝试了这段代码,我们得到了连接的接入点的网关 IP 地址,在我的例子中是 0.0.0.0。但我们想要连接的接入点的 IP 地址而不是其网关 IP。你能帮忙吗? 如何获取 dhcp 服务器 iOS Swift 的 ip 地址? @Akshada-Systematix 我的示例展示了如何访问路由表并获取有关默认网关的信息。路由表包含所有已知的路由,例如主机、子网和默认路由,您可以通过分析其标志从列表中获取所需的路由。 FreeBSD 网关和路由 - docs.freebsd.org/en/books/handbook/advanced-networking/…

以上是关于如何在 Swift iOS 中获取路由器的 IP 地址的主要内容,如果未能解决你的问题,请参考以下文章

Cocoa:如何在 Swift 中获取广播 IP 地址?

Swift - 获取设备的 WIFI IP 地址

如何解决路由器自动获取ip地址失败

如何获取网络中所有设备的名称和 IP 或获取我连接的路由器 IP?

无线路由器设置中无线路由模式的静态IP如何获取?

如何以编程方式在android中获取连接的wifi路由器的IP地址?