以编程方式获取网关和子网掩码详细信息

Posted

技术标签:

【中文标题】以编程方式获取网关和子网掩码详细信息【英文标题】:Programmatically getting the gateway and subnet mask details 【发布时间】:2011-07-20 05:04:51 【问题描述】:

如何在 android 中获取网关和子网掩码详细信息?

【问题讨论】:

你的意思是你需要读取WiFi中的网络参数信息吗?还是您的意思是为 GPRS 或 EDGE 等移动网络连接阅读它?? @AndroidKid 有什么方法可以读取 GPRS/EDGE/3G 吗? @prongs 可以使用测试菜单查看蜂窝连接信息。以下是打开拨号程序的步骤。拨#*#4636#*# 打开“测试”屏幕。点击电话信息。向下滚动以查看您的 IP、网关和 DNS 详细信息 【参考方案1】:

此版本适用于任何网络(Wifi/Cell)。返回 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】:

这是一个旧线程,但我找到了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()

【讨论】:

【参考方案3】:

虽然老了,但很有魅力。

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

【讨论】:

【参考方案4】:

而不是获得 255.255.255.0,只需更改顺序作为回报;)因此您将能够以正确的顺序获得...

public String intToIp(int i) 

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

【讨论】:

【参考方案5】:

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

描述场景的示例图片:

****这里是一个示例代码:**

**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 从整数形式转换为 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

【讨论】:

由于某种原因,子网掩码似乎是相反的,即 0.255.255.255 而不是 255.255.255.0 在我的情况下。 @Czechnology 你可以使用Formatter.formatIpAddress(&lt;yourIpAsInteger); @Schoentoon 并且这个类在 API 19 中被标记为 undeprecated。 是的,这很奇怪。 Goggle 表示 API 18 已弃用。但是对于API 19,它不再被弃用了。 在 Lollipop 上时,网络掩码总是返回 0.. 任何解决方案..?【参考方案6】:

Formatter.formatIpAddress(int) 已弃用,我们不想使用已弃用的方法吗?

AndroidKid 的这个版本在某种程度上被颠倒了,但这应该可以解决它:

public String intToIp(int addr) 
    return  ((addr & 0xFF) + "." + 
            ((addr >>>= 8) & 0xFF) + "." + 
            ((addr >>>= 8) & 0xFF) + "." + 
            ((addr >>>= 8) & 0xFF));

来源:http://www.devdaily.com/java/jwarehouse/android/core/java/android/net/DhcpInfo.java.shtml

【讨论】:

也许使用 StringBuffer 而不是使用运算符 "+" 的六个字符串连接会更有效(对于每个连接都使用后者先前的 String-object 被丢弃并创建了一个新的 String-object),请参阅this gist 在这种情况下,编译器实际上会创建一个字符串缓冲区并附加字符串。所以没关系。但是,如果您在迭代中使用该方法,例如: for(int i = 0; i 【参考方案7】:

使用Formatter.formatIpAddress(mask); 掩码是你的int。

String maskk = Formatter.formatIpAddress(mask);

【讨论】:

【参考方案8】:

要格式化 ip,请尝试使用:

import android.text.format.Formatter;

public String FormatIP(int IpAddress)

    return Formatter.formatIpAddress(IpAddress);

【讨论】:

此方法已弃用...developer.android.com/reference/android/text/format/… 由于 IPv6 而弃用,但适用于 IPv4。您可以选择另一种方式,尤其适用于 IPv6。

以上是关于以编程方式获取网关和子网掩码详细信息的主要内容,如果未能解决你的问题,请参考以下文章

delphi 获取IP,子网,网关,DNS

怎样用Java验证ip和子网掩码是不是正确,详细问题如下

如何以编程方式获取完整的 ios 设备详细信息

如何获取局域网内主机信息-连接网络帐号\密码

在 Java 代码中获取错误以查找有关子网和掩码的信息 [重复]

知道ip地址与子网 怎样算网络号与主机号 详细点