Android获取本机IP地址

1、layout页面

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btnGetIP"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="获取本机IP" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <EditText
            android:id="@+id/txtResult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textMultiLine"
            android:lines="5" >

            <requestFocus />
        </EditText>

    </LinearLayout>

</LinearLayout>

2、AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.phonetest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="18" />
    
    
		
		<!-- permission -->
    
		<uses-permission android:name="android.permission.INTERNET" />
    
		<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
		<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    
		<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    
		<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    
		<uses-permission android:name="android.permission.WAKE_LOCK" />
   
		
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        
		android:debuggable="true" >
        <activity
            android:name="com.example.phonetest.MainActivity"
            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>

</manifest>

3、Activity类

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);	
		init();
	}

	private void init(){
		final TextView txtResult = (TextView)findViewById(R.id.txtResult);
		
		//btnStart
		Button btnGetIP = (Button)findViewById(R.id.btnGetIP);
        View.OnClickListener listener1 = new View.OnClickListener(){
            @Override
            public void onClick(View v) {
            	String address = null;
            	try{
            		address = getIPAddress();
            	}catch(Exception ex){
        			Log.e("MainActivity", ex.getMessage());
        			address = "error: " + ex.getMessage();
            	}
            	txtResult.setText(address);
            }
        };
        btnGetIP.setOnClickListener(listener1);
	}

	private String getIPAddress() throws SocketException {
		String address = null;
		ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if(networkInfo != null && networkInfo.isConnected()){
			if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){//2G,3G,4G
				address = getIPAddressForNetwork();
			}else if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){//WIFI
				address = getIPAddressForWifi();
			}
		}
		return address;
	}

	private String getIPAddressForNetwork() throws SocketException {
		String address = null;
		for(Enumeration<NetworkInterface> enum1=NetworkInterface.getNetworkInterfaces(); enum1.hasMoreElements();){
			NetworkInterface networkInterface = enum1.nextElement();
			for(Enumeration<InetAddress> enum2=networkInterface.getInetAddresses(); enum2.hasMoreElements();){
				InetAddress inetAddress = enum2.nextElement();
				if(!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address){
					address = "type: 手机网络\n本机IP: " + inetAddress.getHostAddress().toString();
				}
			}
		}
		return address;
	}
	
	private String getIPAddressForWifi() {
		WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
		
		if(!wifiManager.isWifiEnabled()){
			wifiManager.setWifiEnabled(true);
		}
		
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String address = "type: WIFI\nIP地址: " + intIP2String(wifiInfo.getIpAddress()) + "\nMAC地址:" + wifiInfo.getMacAddress();
		return address;
	}
	
	private String intIP2String(int ip){
		return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 24) & 0xFF);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

相关推荐