以编程方式获取网关和子网掩码详情

42

我该如何在Android中获取网关和子网掩码信息?


你的意思是需要读取Wi-Fi网络参数的信息吗?还是需要读取移动网络连接(如GPRS或EDGE)的信息? - Anoop Chandrika HarisudhanNair
1
@AndroidKid 有没有办法通过GPRS/EDGE/3G来阅读它? - prongs
@prongs 有一种方法可以使用测试菜单查看蜂窝连接信息。以下是步骤:打开拨号器。拨打##4636##以打开“测试”屏幕。点击“电话信息”。向下滚动以查看您的IP、网关和DNS详细信息。 - Anoop Chandrika HarisudhanNair
8个回答

81

我在android.net包中找到了一个名为DhcpInfo的类。它有一些公共变量,存储当前网络参数的值。但问题是它们返回的值是从8位移位二进制转换而来的整数。

描述场景的示例图像:

输入图像描述

下面是样例代码:

**Java文件:**

package com.schogini.dhcp;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.net.*;
import android.net.wifi.WifiManager;

public class dhcpInfo extends Activity {
    public String   s_dns1 ;
    public String   s_dns2;     
    public String   s_gateway;  
    public String   s_ipAddress;    
    public String   s_leaseDuration;    
    public String   s_netmask;  
    public String   s_serverAddress;
    TextView info;
    DhcpInfo d;
    WifiManager wifii;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wifii= (WifiManager) getSystemService(Context.WIFI_SERVICE);
        d=wifii.getDhcpInfo();

        s_dns1="DNS 1: "+String.valueOf(d.dns1);
        s_dns2="DNS 2: "+String.valueOf(d.dns2);    
        s_gateway="Default Gateway: "+String.valueOf(d.gateway);    
        s_ipAddress="IP Address: "+String.valueOf(d.ipAddress); 
        s_leaseDuration="Lease Time: "+String.valueOf(d.leaseDuration);     
        s_netmask="Subnet Mask: "+String.valueOf(d.netmask);    
        s_serverAddress="Server IP: "+String.valueOf(d.serverAddress);

        //dispaly them
        info= (TextView) findViewById(R.id.infolbl);
        info.setText("Network Info\n"+s_dns1+"\n"+s_dns2+"\n"+s_gateway+"\n"+s_ipAddress+"\n"+s_leaseDuration+"\n"+s_netmask+"\n"+s_serverAddress);
    }
}

XML 编程:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.schogini.dhcp"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="4" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".dhcpInfo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
</manifest>

我尝试将整数值转换为其等效的IP地址,但失败了。如果您能够实现,请回复。再见。

更新:我已经设法将IP地址从整数形式转换为v4格式
转换为IPv4格式:

public String intToIp(int i) {

   return ((i >> 24 ) & 0xFF ) + "." +
               ((i >> 16 ) & 0xFF) + "." +
               ((i >> 8 ) & 0xFF) + "." +
               ( i & 0xFF) ;
}

图片来源: http://www.bennadel.com/blog/1830-Converting-IP-Addresses-To-And-From-Integer-Values-With-ColdFusion.htm


6
由于某种原因,我的子网掩码似乎相反了,即在我的情况下是0.255.255.255而不是255.255.255.0 - Czechnology
1
@Czechnology 你可以使用 Formatter.formatIpAddress(<yourIpAsInteger); - Simon Dorociak
3
这个类在API 19中被标记为未过时。 - GrAnd
1
是的,这很奇怪。谷歌说在API 18中它已经被弃用了。但在API 19中它又没有被弃用了。 - GrAnd
3
当在棒棒糖(Android 5.0)上运行时,netmask 总是返回 0。有解决方法吗? - Sagar D
显示剩余15条评论

14

也许使用_StringBuffer_比使用六个带有运算符_"+"_的字符串连接更加高效(对于后者,每次连接都会丢弃前一个String对象并创建一个新的String对象),请参见此代码片段 - user1364368
1
编译器实际上会创建一个字符串缓冲区,并在这种情况下追加字符串。所以这没关系。但是,如果您像这样在迭代中使用该方法:for(int i = 0; i<10; i++) intToIp(addr[i]); 那么它将创建六次十个字符串。 - rtc11

5

格式化 IP 地址,可以尝试使用以下方法:

import android.text.format.Formatter;

public String FormatIP(int IpAddress)
{
    return Formatter.formatIpAddress(IpAddress);
}

6
这种方法已被弃用... http://developer.android.com/reference/android/text/format/Formatter.html#formatIpAddress%28int%29 - Anoop Chandrika HarisudhanNair
它因IPv6而被弃用,但对于IPv4仍然有效。你可以选择另一种方式,特别是针对IPv6。 - Simon Dorociak

5

这是一个旧的线程,但我找到了Android API(包android.net.NetworkUtils)使用的官方函数:

/**
 * Convert a IPv4 address from an integer to an InetAddress.
 * @param hostAddress an int corresponding to the IPv4 address in network byte order
 */
public static InetAddress intToInetAddress(int hostAddress) {
    byte[] addressBytes = { (byte)(0xff & hostAddress),
                            (byte)(0xff & (hostAddress >> 8)),
                            (byte)(0xff & (hostAddress >> 16)),
                            (byte)(0xff & (hostAddress >> 24)) };

    try {
       return InetAddress.getByAddress(addressBytes);
    } catch (UnknownHostException e) {
       throw new AssertionError();
    }
}

一旦你获取了InetAddress,你可以按照以下方式得到格式化的字符串:

intToInetAddress(d.gateway).getHostAddress()


4

使用Formatter.formatIpAddress(mask);,其中mask为您的整数。

String maskk = Formatter.formatIpAddress(mask);

3

这个版本适用于任何网络(Wifi/蜂窝数据)。返回V4和V6。

/**
 * Returns the set of all gateways<V4 & V6> for any Network
 *
 */
fun getGatewaySet(network:Network, context:Context):MutableSet<InetAddress> {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    connectivityManager.getLinkProperties(network)?.routes?.let {
        //Saw dupes on my device, so use a set
        val set = mutableSetOf<InetAddress>()
        for (routeInfo in it) {
            routeInfo?.gateway?.let { inetAddress ->
                //If comes from AOSP isGateway() - requires API 29
                if (!inetAddress.isAnyLocalAddress) {
                    set.add(inetAddress)
                }
            }
        }
        return set
    }
    return Collections.EMPTY_SET as MutableSet<InetAddress>
}

2

不要获取255.255.255.0,只需更改返回顺序即可;)这样你就可以按正确顺序获取...

public String intToIp(int i) {

   return (i & 0xFF) + "." +
               ((i >> 8 ) & 0xFF) + "." +
               ((i >> 16 ) & 0xFF) + "." +
               ((i >> 24 ) & 0xFF) ;
}

-2

虽然旧了,但运行得很好。

tvGateway.setText(Formatter.formatIpAddress(dhcpInfo.gateway));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接