免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 825 | 回复: 0

android获取ip的方法 [复制链接]

论坛徽章:
0
发表于 2011-12-22 08:51 |显示全部楼层
  1. 需要一些uses-permission
  2. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
  3.     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
  4.     <uses-permission android:name="android.permission.INTERNET"></uses-permission>

  5. package com.miles.demo.getipinfo;

  6. import java.net.InetAddress;
  7. import java.net.NetworkInterface;
  8. import java.net.Socket;
  9. import java.util.Enumeration;

  10. import android.app.Activity;
  11. import android.net.wifi.WifiInfo;
  12. import android.net.wifi.WifiManager;
  13. import android.os.Bundle;
  14. import android.text.format.Formatter;
  15. import android.widget.TextView;

  16. public class GetIPinfoActivity extends Activity {
  17.     
  18.     private TextView mText;
  19.     
  20.     @Override
  21.     public void onCreate(Bundle savedInstanceState) {
  22.         super.onCreate(savedInstanceState);
  23.         setContentView(R.layout.main);
  24.         mText = (TextView) findViewById(R.id.text);
  25.         String ip;
  26.         
  27.         //Method 1
  28.         WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
  29.         WifiInfo info = wifiManager.getConnectionInfo();
  30.         ip = "wifiInfo :" + Formatter.formatIpAddress(info.getIpAddress());
  31.         ip += "\n";
  32.         
  33.         //Method 2
  34.         try{
  35.             Socket socket = new Socket("10.40.73.41", 80);
  36.             ip += "socket : " + socket.getLocalAddress().toString() + "\n";
  37.         } catch (Exception e) {
  38.             e.printStackTrace();
  39.             //throw new RuntimeException();
  40.         }
  41.         
  42.         //Method 3
  43.         try {
  44.             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
  45.             NetworkInterface inf = interfaces.nextElement();
  46.             for (Enumeration<InetAddress> enumAddress = inf.getInetAddresses();enumAddress.hasMoreElements();) {
  47.                 InetAddress in = enumAddress.nextElement();
  48.                 if(!in.isLinkLocalAddress()) {
  49.                     ip += "NetworkInterface : " + in.getHostAddress() + "\n";
  50.                 }
  51.             }
  52.         }catch (Exception e) {
  53.             e.printStackTrace();
  54.             //throw new RuntimeException();
  55.         }
  56.         
  57.         mText.setText("" + ip);
  58.     }
  59. }
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP