当前位置: 首页 > news >正文

android中获取IP的方法

这是看到了Android_Tutor的博客中的内容,就贴过来自己学习下了

public String getLocalIpAddress() {  
    try {  
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {  
            NetworkInterface intf = en.nextElement();  
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {  
                InetAddress inetAddress = enumIpAddr.nextElement();  
                if (!inetAddress.isLoopbackAddress()) {  
                    return inetAddress.getHostAddress().toString();  
                }  
            }  
        }  
    } catch (SocketException ex) {  
        Log.e(LOG_TAG, ex.toString());  
    }  
    return null;  
}  

还有种方法:

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);  
WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
int ipAddress = wifiInfo.getIpAddress();  

wifi的网络,得到一个int值,要再写个int转换ip的方法,就可以得到ip地址了:

public static String longToIP(long longIp) {
// linux long是低位在前,高位在后
StringBuffer sb = new StringBuffer("");
// 将高24位置0
sb.append(String.valueOf((longIp & 0x000000FF)));
sb.append(".");
// 将高16位置0,然后右移8位
sb.append(String.valueOf((longIp & 0x0000FFFF) >>> 8));
sb.append(".");
// 将高8位置0,然后右移16位
sb.append(String.valueOf((longIp & 0x00FFFFFF) >>> 16));
sb.append(".");
// 直接右移24位
sb.append(String.valueOf((longIp >>> 24)));
return sb.toString();
}

 

 

 

来看个完整例子的:

新建工程GetIp,修改/res/layout/main.xml文件,在里面增加一个TextView文本,完整的main.xml文件如下:
1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent"
 6     >
 7
 8      <TextView
 9         android:id="@+id/nametextview"
10         android:layout_width="fill_parent"
11         android:layout_height="wrap_content"
12         android:text=" "
13         android:textSize="20px"
14         />
15
16     <TextView
17         android:id="@+id/ipTextView"
18         android:layout_width="fill_parent"
19         android:layout_height="wrap_content"
20         android:text=" "
21         android:textSize="20px"
22         />
23
24 </LinearLayout>

修改GetIp.java文件,主要是声明一个ConnectivityManager对象和一个NetworkInfo对象,编写一个对话框函数,当用户没有打开网络就运行该程序时,该对话框会提示用户检查网络。

1 package com.nan.getip;
  2
  3 import android.app.Activity;
  4 import android.app.AlertDialog;
  5 import android.content.DialogInterface;
  6 import android.net.ConnectivityManager;
  7 import android.net.NetworkInfo;
  8 import android.os.Bundle;
  9 import java.net.InetAddress;
 10 import java.net.NetworkInterface;
 11 import java.util.Enumeration;
 12 import java.net.SocketException;
 13 import android.util.Log;
 14 import android.widget.TextView;
 15
 16
 17 public class GetIp extends Activity
 18 {
 19     private TextView ipTextView = null;
 20     private TextView nameTextView = null;
 21     //定义一个ConnectivityManager对象
 22     private ConnectivityManager mConnectivityManager = null;
 23     //定义一个NetworkInfo对象
 24     private NetworkInfo mActiveNetInfo = null;
 25
 26     /** Called when the activity is first created. */
 27     @Override
 28     public void onCreate(Bundle savedInstanceState)
 29     {
 30         super.onCreate(savedInstanceState);
 31         setContentView(R.layout.main);
 32
 33         nameTextView = (TextView)findViewById(R.id.nametextview);
 34         ipTextView = (TextView)findViewById(R.id.ipTextView);
 35         //实例化mConnectivityManager对象
 36         mConnectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);//获取系统的连接服务
 37         //实例化mActiveNetInfo对象
 38         mActiveNetInfo = mConnectivityManager.getActiveNetworkInfo();//获取网络连接的信息
 39         if(mActiveNetInfo==null)
 40             myDialog();
 41         else
 42             setUpInfo();
 43
 44     }
 45
 46     //获取本地IP函数
 47     public String getLocalIPAddress()
 48     {
 49         try
 50         {
 51             for (Enumeration<NetworkInterface> mEnumeration = NetworkInterface.getNetworkInterfaces(); mEnumeration.hasMoreElements();)
 52             {
 53                NetworkInterface intf = mEnumeration.nextElement();
 54                for (Enumeration<InetAddress> enumIPAddr = intf.getInetAddresses(); enumIPAddr.hasMoreElements();)
 55                {
 56                    InetAddress inetAddress = enumIPAddr.nextElement();
 57                    //如果不是回环地址
 58                    if (!inetAddress.isLoopbackAddress())
 59                    {
 60                        //直接返回本地IP地址
 61                        return inetAddress.getHostAddress().toString();
 62                    }
 63                }
 64            }
 65         }
 66         catch (SocketException ex)
 67         {
 68             Log.e("Error", ex.toString());
 69         }
 70         return null;
 71     }
 72
 73     //显示IP信息
 74     public void setUpInfo()
 75     {
 76         //如果是WIFI网络
 77         if(mActiveNetInfo.getType()==ConnectivityManager.TYPE_WIFI)
 78         {
 79             nameTextView.setText("网络类型:WIFI");
 80             ipTextView.setText("IP地址:"+getLocalIPAddress());
 81         }
 82         //如果是手机网络
 83         else if(mActiveNetInfo.getType()==ConnectivityManager.TYPE_MOBILE)
 84         {
 85             nameTextView.setText("网络类型:手机");
 86             ipTextView.setText("IP地址:"+getLocalIPAddress());
 87         }
 88         else
 89         {
 90             nameTextView.setText("网络类型:未知");
 91             ipTextView.setText("IP地址:");
 92         }
 93
 94     }
 95
 96     //显示对话框
 97     private void myDialog()
 98     {
 99         AlertDialog mDialog = new AlertDialog.Builder(GetIp.this)
100         .setTitle("注意")
101         .setMessage("当前网络不可用,请检查网络!")
102         .setPositiveButton("确定", new DialogInterface.OnClickListener()
103         {
104
105             @Override
106             public void onClick(DialogInterface dialog, int which)
107             {
108                 // TODO Auto-generated method stub
109                 //关闭对话框
110                 dialog.dismiss();
111                 //结束Activity
112                 GetIp.this.finish();
113             }
114         })
115         .create();//创建这个对话框
116         mDialog.show();//显示这个对话框
117     }
118
119 }
最后,修改AndroidManifest.xml文件,在里面添加2个权限:
 
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

转载于:https://www.cnblogs.com/Tammie/archive/2012/08/15/2640386.html

相关文章:

  • Python中的基础定义
  • 15 款为jQuery Mobile定制的插件推荐
  • JAVA修改常量后服务器上未生效
  • Application对象的使用-数据传递以及内存泄漏问题 和使用Memory Analyzer tool(MAT)
  • 5.2. Spring Data MongoDB
  • HDU ACM 4006 The kth great number (优先队列)
  • 33.5. Apache Kafka is a distributed publish-subscribe messaging system
  • (转)AS3正则:元子符,元序列,标志,数量表达符
  • 35.2. The DOT Language
  • Bash:如何循环含有空格的文件名或文件中的行?
  • 我的2017,我的认证之路
  • 安装 archlinux 之在 BIOS/MBR 基本安装
  • gevent爬取豆瓣电影top250
  • 如何使用js判断浏览器内核然后引用不同的css外联样式
  • c++ DLL和c#之间传递字符串
  • 时间复杂度分析经典问题——最大子序列和
  • 【跃迁之路】【519天】程序员高效学习方法论探索系列(实验阶段276-2018.07.09)...
  • E-HPC支持多队列管理和自动伸缩
  • happypack两次报错的问题
  • Intervention/image 图片处理扩展包的安装和使用
  • MySQL QA
  • PAT A1120
  • Promise面试题2实现异步串行执行
  • React Native移动开发实战-3-实现页面间的数据传递
  • Vue小说阅读器(仿追书神器)
  • Yeoman_Bower_Grunt
  • 飞驰在Mesos的涡轮引擎上
  • 规范化安全开发 KOA 手脚架
  • 技术攻略】php设计模式(一):简介及创建型模式
  • 前端面试题总结
  • 前端相关框架总和
  • 使用SAX解析XML
  • 新海诚画集[秒速5センチメートル:樱花抄·春]
  • ​【C语言】长篇详解,字符系列篇3-----strstr,strtok,strerror字符串函数的使用【图文详解​】
  • (01)ORB-SLAM2源码无死角解析-(56) 闭环线程→计算Sim3:理论推导(1)求解s,t
  • (C++)栈的链式存储结构(出栈、入栈、判空、遍历、销毁)(数据结构与算法)
  • (webRTC、RecordRTC):navigator.mediaDevices undefined
  • (ZT)出版业改革:该死的死,该生的生
  • (篇九)MySQL常用内置函数
  • (三)uboot源码分析
  • (四)Android布局类型(线性布局LinearLayout)
  • *++p:p先自+,然后*p,最终为3 ++*p:先*p,即arr[0]=1,然后再++,最终为2 *p++:值为arr[0],即1,该语句执行完毕后,p指向arr[1]
  • .cn根服务器被攻击之后
  • .net core 源码_ASP.NET Core之Identity源码学习
  • .net 获取url的方法
  • .NET 设计模式初探
  • .NET 指南:抽象化实现的基类
  • .NET 中小心嵌套等待的 Task,它可能会耗尽你线程池的现有资源,出现类似死锁的情况
  • .NET设计模式(11):组合模式(Composite Pattern)
  • :not(:first-child)和:not(:last-child)的用法
  • @AliasFor注解
  • @Autowired @Resource @Qualifier的区别
  • @Autowired标签与 @Resource标签 的区别
  • @Transactional类内部访问失效原因详解
  • [ C++ ] STL---仿函数与priority_queue