Si devono per prima cosa impostare i permessi
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
--------------------------------------------------------
package com.example.ip;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView ip_t;
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 (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip_t = (TextView) findViewById(R.id.ip);
String ip = getLocalIpAddress();
ip_t.setText(ip);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
--------------------------------------------------------
Se si esegue il programma sull'emulatore Android l'indirizzo IP mostrato e' 10.0.2.15 che tradisce chiaramente il fatto che l'emulatore stesso discenda direttamente da QEmu
Nessun commento:
Posta un commento