要在有网络的情况下获取,无网络通常无法获取网关ip
nw_path_monitor_t path_monitor = nw_path_monitor_create();
nw_path_monitor_set_update_handler(path_monitor, ^(nw_path_t path) {
if (!nw_path_is_expensive(path) && nw_path_status(path) == nw_path_status_satisfied) {
nw_path_enumerate_gateways(path, ^bool(nw_endpoint_t gateway) {
const struct sockaddr *address = nw_endpoint_get_address(gateway);
if (address->sa_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4Address = (struct sockaddr_in *)address;
char gatewayAddressBuffer[INET_ADDRSTRLEN];
const char *gatewayAddressString = inet_ntop(AF_INET, &(ipv4Address->sin_addr), gatewayAddressBuffer, INET_ADDRSTRLEN);
if (gatewayAddressString != NULL) {
NSString *gatewayAddress = [NSString stringWithUTF8String:gatewayAddressString];
NSLog(@"Gateway Address: %@", gatewayAddress);
}
} else if (address->sa_family == AF_INET6) { // IPv6
struct sockaddr_in6 *ipv6Address = (struct sockaddr_in6 *)address;
char gatewayAddressBuffer[INET6_ADDRSTRLEN];
const char *gatewayAddressString = inet_ntop(AF_INET6, &(ipv6Address->sin6_addr), gatewayAddressBuffer, INET6_ADDRSTRLEN);
if (gatewayAddressString != NULL) {
NSString *gatewayAddress = [NSString stringWithUTF8String:gatewayAddressString];
NSLog(@"Gateway Address: %@", gatewayAddress);
}
}
return NO;
});
} else {
NSLog(@"No active network connection.");
}
});
nw_path_monitor_set_queue(path_monitor, dispatch_get_main_queue());
nw_path_monitor_start(path_monitor);