2016-06-23 33 views

回答

0

是的,这是可能的。您可以通过编程检查活动网络接口。例如。与this代码:

/* 
    Example code to obtain IP and MAC for all available interfaces on Linux. 
    by Adam Pierce <[email protected]> 

http://www.doctort.org/adam/ 

*/ 

#include <sys/ioctl.h> 
#include <net/if.h> 
#include <netinet/in.h> 
#include <stdio.h> 
#include <arpa/inet.h> 

int main(void) 
{ 
    char   buf[1024]; 
    struct ifconf ifc; 
    struct ifreq *ifr; 
    int   sck; 
    int   nInterfaces; 
    int   i; 

/* Get a socket handle. */ 
    sck = socket(AF_INET, SOCK_DGRAM, 0); 
    if(sck < 0) 
    { 
     perror("socket"); 
     return 1; 
    } 

/* Query available interfaces. */ 
    ifc.ifc_len = sizeof(buf); 
    ifc.ifc_buf = buf; 
    if(ioctl(sck, SIOCGIFCONF, &ifc) < 0) 
    { 
     perror("ioctl(SIOCGIFCONF)"); 
     return 1; 
    } 

/* Iterate through the list of interfaces. */ 
    ifr   = ifc.ifc_req; 
    nInterfaces = ifc.ifc_len/sizeof(struct ifreq); 
    for(i = 0; i < nInterfaces; i++) 
    { 
     struct ifreq *item = &ifr[i]; 

    /* Show the device name and IP address */ 
     printf("%s: IP %s", 
       item->ifr_name, 
       inet_ntoa(((struct sockaddr_in *)&item->ifr_addr)->sin_addr)); 

    /* Get the MAC address */ 
     if(ioctl(sck, SIOCGIFHWADDR, item) < 0) 
     { 
      perror("ioctl(SIOCGIFHWADDR)"); 
      return 1; 
     } 

    /* Get the broadcast address (added by Eric) */ 
     if(ioctl(sck, SIOCGIFBRDADDR, item) >= 0) 
      printf(", BROADCAST %s", inet_ntoa(((struct sockaddr_in *)&item->ifr_broadaddr)->sin_addr)); 
     printf("\n"); 
    } 

     return 0; 
} 

你可以编译为Android,然后通过ADB外壳推出。在我的设备它给下一个输出:

[email protected]:/ $ /data/local/tmp/ifenum           
lo: IP 127.0.0.1, BROADCAST 0.0.0.0 
rmnet_usb0: IP 100.105.60.161, BROADCAST 0.0.0.0 
wlan0: IP 192.168.0.100, BROADCAST 192.168.0.255 

正如你看到的,我的设备连接到两个不同的网络,我可以自由选择使用什么。 (rmnet_usb0由我的移动运营商提供,实际上是Edge网络,但IMO 3G以相同结果结束)

P.S.大多数应用程序不关心他们使用的接口并将它们的套接字绑定到INADDR_ANY,显然系统将使用可用网络的“最佳”。

+0

好吧tnx很多...当我得到像你这样的所有网络,我可以发送数据包(传输),例如在3G和WIFI接收?谢谢你的帮助... @Serhio – Royal

+0

@Ryali一般 - 没有。每个创建的套接字只使用一个网络接口进行传输和接收。您可以通过创建两个连接来解决它,然后将它们绑定到设备上的不同接口。但在这种情况下,远程端应该手动选择正确的连接,从中读取请求并将其写入应答。 – Sergio

相关问题