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

发布于 2024-10-24 05:16:16 字数 34 浏览 1 评论 0原文

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

How can I get gateway and subnet mask details in Android?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

凝望流年 2024-10-31 05:16:16

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

I have found a class called DhcpInfo within the android.net package. It has some public variables that stores the values of current Network parameters. But the problem is they return the value in integer converted from 8Bit shifted binary.

Sample Image Describing thee Scenario:

enter image description here

****Here is a sample code:**

**java file:****

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 Coding:

<?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>

I tried converting the integer value to its equivalent but i couldn't. If you do so you can post back.. Bye..

UPDATE: Some how managed to convert the IP to v4 Format from the integer form
Conversion to IPv4 Format:

public String intToIp(int i) {

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

IMAGE Courtesy: http://www.bennadel.com/blog/1830-Converting-IP-Addresses-To-And-From-Integer-Values-With-ColdFusion.htm

百善笑为先 2024-10-31 05:16:16

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

AndroidKid 的版本在某种程度上是相反的,但这应该可以修复它:

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

来源:

Formatter.formatIpAddress(int) is deprecated, and we dont want to use deprecated methods do we?

AndroidKid's version of this is somehow reversed, but this should fix it:

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

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

电影里的梦 2024-10-31 05:16:16

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

import android.text.format.Formatter;

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

to format the ip, try using:

import android.text.format.Formatter;

public String FormatIP(int IpAddress)
{
    return Formatter.formatIpAddress(IpAddress);
}
通知家属抬走 2024-10-31 05:16:16

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

This is an old Thread, but I found the official function used by android API (package 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();
    }
}

And once you have InetAddress you can get the formatted String this way:

intToInetAddress(d.gateway).getHostAddress()

森林散布 2024-10-31 05:16:16

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

String maskk = Formatter.formatIpAddress(mask);

Use Formatter.formatIpAddress(mask); mask is your int.

String maskk = Formatter.formatIpAddress(mask);
花间憩 2024-10-31 05:16:16

此版本适用于任何网络(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>
}

This version works with any Network (Wifi/Cell). Returns V4 and 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>
}
〆一缕阳光ご 2024-10-31 05:16:16

不要获取 255.255.255.0,只需更改返回的顺序即可;)这样您将能够获得正确的顺序...

public String intToIp(int i) {

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

Instead of getting 255.255.255.0, just change the order in return ;) So you will be able to get in the right order...

public String intToIp(int i) {

   return (i & 0xFF) + "." +
               ((i >> 8 ) & 0xFF) + "." +
               ((i >> 16 ) & 0xFF) + "." +
               ((i >> 24 ) & 0xFF) ;
}
ぶ宁プ宁ぶ 2024-10-31 05:16:16

虽然老了,但仍然有魅力。

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

Although old, works like a charm.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文