美文网首页
iOS切换网卡(eg:在连接wifi的情况下,通过蜂窝网络发送请

iOS切换网卡(eg:在连接wifi的情况下,通过蜂窝网络发送请

作者: novaDev | 来源:发表于2017-10-13 12:55 被阅读0次

可以使用IP_BOUND_IF的方式,切换网卡:

  1. 使用"ifaddrs.h"中的"getifaddrs"来获取interface addresses
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    NSInteger success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Get NSString from C String
                NSString* ifaName = [NSString stringWithUTF8String:temp_addr->ifa_name];
                NSString* address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_addr)->sin_addr)];
                NSString* mask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_netmask)->sin_addr)];
                NSString* gateway = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_dstaddr)->sin_addr)];
                NSLog(@"%@;%@;%@;%@",ifaName,address,mask,gateway);
            }
            temp_addr = temp_addr->ifa_next;
        }
    }

然后你将会在控制台看见类似如下信息:

lo0;127.0.0.1;255.0.0.0;127.0.0.1  
pdp_ip0;10.9.163.185;255.255.255.255;10.9.163.185  
en0;10.0.0.6;255.255.0.0;10.0.255.255 

("pdp_ip0" 代表了蜂窝网络)

  1. 使用"net/if.h"中的"if_nametoindex"和"sys/socket.h"中的"setsockopt",向特定的interface发送消息
    int s = socket(AF_INET, SOCK_STREAM, 0); 
    int index = if_nametoindex( "pdp_ip0");
    int suc = setsockopt(s, IPPROTO_IP, IP_BOUND_IF, &index, sizeof(index));

随后可以使用socket进行网络连接,后续操作本人没有进一步调研,但是根据以上信息一定可以通过特定网卡进行网络连接

相关文章

网友评论

      本文标题:iOS切换网卡(eg:在连接wifi的情况下,通过蜂窝网络发送请

      本文链接:https://www.haomeiwen.com/subject/fyrzyxtx.html