2021年4月29日 星期四

Android Studio get device ip

 Get the device ip function


Append the permission for AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Create an app with a button and a textview.

public class MainActivity extends AppCompatActivity {
TextView txt_log;
Button btn_get_ip;
Button btn_ping_ip;
Button btn_check_url_alive;
Button btn_clean_log;
String device_ip = "192.168.1.10";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Asign the items
txt_log = findViewById(R.id.txt_log);
btn_get_ip = findViewById(R.id.btn_get_ip);
btn_ping_ip = findViewById(R.id.btn_ping_ip);
btn_check_url_alive = findViewById(R.id.btn_check_url_alive);
btn_clean_log = findViewById(R.id.btn_clean_log);

// Initial item
txt_log.setMovementMethod(new ScrollingMovementMethod());

// Asign the click function of all items
btn_get_ip.setOnClickListener(btn_get_ip_click);
btn_ping_ip.setOnClickListener(btn_ping_ip_click);
btn_check_url_alive.setOnClickListener(btn_check_url_alive_click);
btn_clean_log.setOnClickListener(btn_clean_log_click);

txt_log.append("App created\n");
}
private View.OnClickListener btn_get_ip_click = new View.OnClickListener() {
@Override
public void onClick(View v) {
txt_log.append("btn_get_ip clicked\n");

String ipAddress = wifiIpAddress(getApplicationContext());
txt_log.append(ipAddress +"\n");
device_ip = ipAddress;
txt_log.append("Set device ip = " + ipAddress +"\n");

int [] ipDot = getDetailsWifiInfo(getApplicationContext());
device_ip = ipDot[0] +"."+ ipDot[1] +"."+ ipDot[2] +".245";
txt_log.append("Set device ip = " + device_ip +"\n");
//txt_log.append(ipDot[0] +"\n");
//txt_log.append(ipDot[1] +"\n");
//txt_log.append(ipDot[2] +"\n");
//txt_log.append(ipDot[3] +"\n");
}
};

private View.OnClickListener btn_ping_ip_click = new View.OnClickListener() {
@Override
public void onClick(View v) {
txt_log.append("btn_ping_ip clicked\n");

String ret = executeCmd("ping -c 1 -w 1 " + device_ip, false);
txt_log.append(ret +"\n");
}
};

private View.OnClickListener btn_check_url_alive_click = new View.OnClickListener() {
@Override
public void onClick(View v) {
txt_log.append("btn_check_url_alive_click\n");

int [] ipDot = getDetailsWifiInfo(getApplicationContext());
for(int cnt =240; cnt < 246; cnt++){
String url_link = "http://"+ ipDot[0] +"."+ ipDot[1] +"."+ ipDot[2] +"." + cnt +"/";
//txt_log.append(url_link + "\n");
new JsonTask().execute(url_link);
}
}
};

private View.OnClickListener btn_clean_log_click = new View.OnClickListener() {
@Override
public void onClick(View v) {
txt_log.setText("");
}
};

protected String wifiIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
//txt_log.append(String.valueOf(ipAddress) +"\n" );

// Convert little-endian to big-endianif needed
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
//txt_log.append(String.valueOf(ipAddress) +"\n" );
}

byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();

String ipAddressString;
try {
ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
//txt_log.append(ipAddressString +"\n" );
} catch (UnknownHostException ex) {
txt_log.append("WIFIIP Unable to get host address.");
ipAddressString = null;
}

return ipAddressString;
}

private int [] getDetailsWifiInfo(Context mContext) {
try {
WifiManager wifiManager = (WifiManager) mContext.getSystemService(WIFI_SERVICE);
WifiInfo mWifiInfo = wifiManager.getConnectionInfo();
int ip = mWifiInfo.getIpAddress();

int [] ret = new int[4];
int ip_01 = (ip & 0xFF);
int ip_02 = ((ip >> 8) & 0xFF);
int ip_03 = ((ip >> 16) & 0xFF);
int ip_04 = ((ip >> 24) & 0xFF);
ret[0] = ip_01;
ret[1] = ip_02;
ret[2] = ip_03;
ret[3] = ip_04;
String strIp = "" + (ip_01) + "." + (ip_02) + "." + (ip_03) + "." + (ip_04);

//txt_log.append(ip_01 +"\n");
//txt_log.append(ip_02 +"\n");
//txt_log.append(ip_03 +"\n");
//txt_log.append(ip_04 +"\n");
return ret;
} catch (Exception e) {
txt_log.append(e.toString() + "\n");
}
return null;
}

//

public static String executeCmd(String cmd, boolean sudo){
try {

Process p;
if(!sudo)
p= Runtime.getRuntime().exec(cmd);
else{
p= Runtime.getRuntime().exec(new String[]{"su", "-c", cmd});
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

String s;
String res = "";
while ((s = stdInput.readLine()) != null) {
res += s + "\n";
}
p.destroy();
return res;
} catch (Exception e) {
e.printStackTrace();
}
return "";

}

public boolean exists(String URLName) {
try {
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
txt_log.append("responseCode:" + responseCode +"\n");
//InputStream in = new BufferedInputStream(urlConnection.getInputStream());
//txt_log.append(in.toString() +"\n");
//readStream(in);
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}

try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con = (HttpURLConnection) new URL(URLName)
.openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}


private class JsonTask extends AsyncTask<String, String, String> {
ProgressDialog pd;
HttpURLConnection connection = null;
String url_link;
protected void onPreExecute() {
super.onPreExecute();

pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}

protected String doInBackground(String... params) {
BufferedReader reader = null;

try {
url_link = params[0];
URL url = new URL(url_link);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);
connection.connect();


InputStream stream = connection.getInputStream();

reader = new BufferedReader(new InputStreamReader(stream));

StringBuffer buffer = new StringBuffer();
String line = "";

while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
//Log.d("Response:", "> " + line + "\n");
//txt_log.append("Response: > " + line + "\n"); //here u ll get whole response...... :-)

}
return buffer.toString();


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
try {
Log.d("Response:", "> " + connection.getResponseCode() + "\n");
txt_log.append(url_link +"->" + connection.getResponseCode() + "\n");
if (connection != null) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
//txt_log.append(result + "\n");
}
}
}

沒有留言: