gpt4 book ai didi

ios - 如何在Objective C中获取路由器IP地址?

转载 作者:行者123 更新时间:2023-12-01 20:21:12 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to get the WIFI gateway address on the iPhone? [duplicate]

(4 个回答)


6年前关闭。




我一直在查看 StackOverflow,但我还没有找到以编程方式在 iOS 中获取 Wifi 路由器 IP 地址的方法。这可能吗?如果是这样,我将如何去做?

最佳答案

#include <stdio.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <string.h>
#include <arpa/inet.h>

#if TARGET_IPHONE_SIMULATOR
#include <net/route.h>
#else
#include "route.h"
#endif

#define CTL_NET 4 /* network, see socket.h */

#if defined(BSD) || defined(__APPLE__)

#define ROUNDUP(a) \
((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))

static int getdefaultgateway(in_addr_t * addr)
{
int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET,
NET_RT_FLAGS, RTF_GATEWAY};
size_t l;
char * buf, * p;
struct rt_msghdr * rt;
struct sockaddr * sa;
struct sockaddr * sa_tab[RTAX_MAX];
int i;
int r = -1;
if(sysctl(mib, sizeof(mib)/sizeof(int), 0, &l, 0, 0) < 0) {
return -1;
}
if(l>0) {
buf = malloc(l);
if(sysctl(mib, sizeof(mib)/sizeof(int), buf, &l, 0, 0) < 0) {
return -1;
}
for(p=buf; p<buf+l; p+=rt->rtm_msglen) {
rt = (struct rt_msghdr *)p;
sa = (struct sockaddr *)(rt + 1);
for(i=0; i<RTAX_MAX; i++) {
if(rt->rtm_addrs & (1 << i)) {
sa_tab[i] = sa;
sa = (struct sockaddr *)((char *)sa + ROUNDUP(sa->sa_len));
} else {
sa_tab[i] = NULL;
}
}

if( ((rt->rtm_addrs & (RTA_DST|RTA_GATEWAY)) == (RTA_DST|RTA_GATEWAY))
&& sa_tab[RTAX_DST]->sa_family == AF_INET
&& sa_tab[RTAX_GATEWAY]->sa_family == AF_INET) {


if(((struct sockaddr_in *)sa_tab[RTAX_DST])->sin_addr.s_addr == 0) {
char ifName[128];
if_indextoname(rt->rtm_index,ifName);

if(strcmp("en0",ifName)==0){

*addr = ((struct sockaddr_in *)(sa_tab[RTAX_GATEWAY]))->sin_addr.s_addr;
r = 0;
}
}
}
}
free(buf);
}
return r;
}

static NSString* routerIP()
{
struct in_addr gatewayaddr;
int r = getdefaultgateway(&(gatewayaddr.s_addr));
if (r >= 0) {
return [NSString stringWithFormat: @"%s",inet_ntoa(gatewayaddr)];
}

return nil;
}

#endif

来自 https://stackoverflow.com/a/9173849/4069848

更新 : route.h 的条件编译

更新 : 如果你想得到一个特定接口(interface)的网关,只需在这一行更改接口(interface)名称:
if(strcmp("en0",ifName)==0){

关于ios - 如何在Objective C中获取路由器IP地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com