Friday, February 7, 2014

Get my IP Address

It's a example to list IP address of Android device.

my IP Address
my IP Address

package com.example.androidmyip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 TextView info;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  info = (TextView)findViewById(R.id.info);
  
  info.setText(getIpAddress());
  //info.setText(getLocalIpAddress());
 }
 
 private String getIpAddress(){
  String ip = "";
  try {
   Enumeration<NetworkInterface> enumNetworkInterfaces = 
     NetworkInterface.getNetworkInterfaces();
   while(enumNetworkInterfaces.hasMoreElements()){
    NetworkInterface networkInterface = 
      enumNetworkInterfaces.nextElement();
    Enumeration<InetAddress> enumInetAddress = 
      networkInterface.getInetAddresses();
    while(enumInetAddress.hasMoreElements()){
     InetAddress inetAddress = enumInetAddress.nextElement();
     
     String ipAddress = "";
     if(inetAddress.isLoopbackAddress()){
      ipAddress = "LoopbackAddress: ";
     }else if(inetAddress.isSiteLocalAddress()){
      ipAddress = "SiteLocalAddress: ";
     }else if(inetAddress.isLinkLocalAddress()){
      ipAddress = "LinkLocalAddress: ";
     }else if(inetAddress.isMulticastAddress()){
      ipAddress = "MulticastAddress: ";
     }
     ip += ipAddress + inetAddress.getHostAddress() + "\n"; 
    }
    
   }
   
  } catch (SocketException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   ip += "Something Wrong! " + e.toString() + "\n";
  }
  
  return ip;
 }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    
    <TextView
        android:id="@+id/info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Remark: <uses-permission android:name="android.permission.INTERNET"/> is needed in AndroidManifest.xml.

download filesDownload the files.

No comments:

Post a Comment