I want to get the ip address of my pc in android emulator through code....or tell me to achive ip address of all devices connected in a lan to identify each one uniquely .......please help me to sort out this problem
Thanks in advance
The above functions are possible only by checking the arp cache where the IP address will be added one by one depending on how each one connect to the device. USe the below code and check. Just put button with proper name and call this method on click
public void getClientList() {
int macCount = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
// Basic sanity check
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
macCount++;
ClientList.add("Client(" + macCount + ")");
IpAddr.add(splitted[0]);
HWAddr.add(splitted[3]);
Device.add(splitted[5]);
Toast.makeText(
getApplicationContext(),
"Mac_Count " + macCount + " MAC_ADDRESS "
+ mac, Toast.LENGTH_SHORT).show();
for (int i = 0; i < splitted.length; i++)
System.out.println("Addressssssss "
+ splitted[i]);
}
}
}
// ClientList.remove(0);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
use this code fetch the external ip address
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://api.externalip.net/ip/");
HttpResponse response = null;
try
{
response = httpclient.execute(httpget);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Log.e("",""+response);
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len != -1 && len < 1024)
{
try
{
str=EntityUtils.toString(entity);
Log.e("",""+str);
}
catch (ParseException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Related
I am connected to a Server whose address is 192.168.1.254 and on typing this address in the browser it is showing the list of available folder
i want to display the name of the folder in my android application i have tried the following code but no-luck.
try {
SmbFile test = new SmbFile("smb://192.168.1.254");
SmbFile[] files = test.listFiles();
if (files != null)
for (SmbFile s : files) {
Log.d("debug", s.getName());
}
} catch (SmbException e) {
Log.d("debug", "ERROR");
} catch (Exception e) {
Log.d("debug", "ERROR");
}
which i find here
and i also tried
File f = new File("//192.168.1.254");
//also tried with File f = new File("http//192.168.1.254");
File[] files = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
// Specify the extentions of files to be included.
return name.endsWith(".bmp") || name.endsWith(".gif");
}
});
// get names of the files
String[] fileNamesArray = null;
for (int indx = 0; indx < files.length(); indx++) {
Log.d("name",files[indx].getName());
}
return fileNamesArray;
Seems you need FTP client for list files on remote location. Try to use, for example, ftp4j library as described in it's official documentation or this Android Example by devert. Exactly list files on remote FTP server with ftp4j by Arun you can find here:
FTPClient client = null;
try { // Get the FTP Connection from the
Utility class client =FTPUtility.connect(ipAddress, userName,
password);
if (client != null) { /* List all file inside the directory */
FTPFile[] fileArray = client.list();
System.out.println("List of files...");
for (int i = 0; i < fileArray.length; i++) {
FTPFile file = fileArray[i];
if (file != null) {
if (file.TYPE_FILE == FTPFile.TYPE_FILE) // File {
System.out.println("File Name = " + file.getName() + " ; File Size = " + file.getSize() + " ;Modified Date = " + file.getModifiedDate());
} else if (file.TYPE_DIRECTORY == FTPFile.TYPE_DIRECTORY) // Directory
{
System.out.println("Directory Name = " + file.getName() + " ; Directory Size = " + file.getSize() + " ;Modified Date = " + file.getModifiedDate());
} else if (file.TYPE_LINK == FTPFile.TYPE_LINK) // Link
{
System.out.println("Link Name = " + file.getName() + " ;Modified Date = "
+ file.getModifiedDate());
}
}
}
}
} catch(
Exception e)
{
System.err.println("ERROR : Error in Connecting to Remote Machine... Hence exitting..."); //
e.printStackTrace();
System.exit(2);
}
finally
{
try {
client.disconnect(true);
} catch
(Exception e) {
}
}
Update
If "there is no active port for ftp , and my current finding is device is having only 4 active port i.e 80,443,3333,8192" seems file list send over HTTP and you can download it via HttpURLConnection and parse response. Something like this:
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://192.168.1.254");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder responseStringBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
responseStringBuilder .append(line);
responseStringBuilder .append("\n");
}
// Parse responseStringBuilder.toString() (probably as HTML) here:
...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
One way is to download html as a string from the server. Then use
urlConnection = new URL("your_url").openConnection();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((String line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
String your_data = Html.fromHtml(stringBuilder.toString());
This will contain the table in text format. You can process it to get the required data.
I am trying to save this boolean array. When I read the array the string array (parts) says that
parts[0]=true;
,but when I use Boolean.parseBoolean array[0] is still false. Can someone help me and tell me what I am doing wrong. Please and Thank You.
public void writeArraytofile() {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("array.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(Arrays.toString(array));
outputStreamWriter.close();
} catch (IOException e) {
Log.v("MyActivity", e.toString());
}
}
public boolean[] read(){
String result = "";
boolean[] array = new boolean[2];
try {
InputStream inputStream = openFileInput("array.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String tempString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((tempString = bufferedReader.readLine()) != null) {
stringBuilder.append(tempString);
}
inputStream.close();
result = stringBuilder.toString();
String[] parts = result.split(" ");
for (int i = 0; i < array.length; i++){
array[i]=Boolean.parseBoolean(parts[i]);
}
}
} catch (FileNotFoundException e) {
Log.v("MyActivity", "File not found" + e.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
//here you catch and watch the problem
Log.e("MyActivity", "cant parse string: " + result);
}
return array;
}
Arrays.toString() will print brackets and commas, so when you read the string back in and call .split(" "), the first piece will be "[true,". Since that is not just "true", Boolean.parseBoolean() will return false.
In Android,
How to get the list of devices connected in same WiFi Network?
How to get the nearest devices from your smartphone connected with same WiFi network?
Did frequency check is able to find the nearest device?
I find the solution for list of devices connected in same network,and i placed the code below
Call this method in onCreate -> getClientList(true, 200);
write this method in our class
public ArrayList<ClientScanResult> getClientList(boolean onlyReachables, int reachableTimeout) {
BufferedReader br = null;
ArrayList<ClientScanResult> result = null;
try {
result = new ArrayList<ClientScanResult>();
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
int i = 0;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if ((splitted != null) && (splitted.length >= 4)) {
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);
if (!onlyReachables || isReachable) {
result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
i++;
}
}
}
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage());
} finally {
try {
br.close();
} catch (IOException e) {
Log.e(this.getClass().toString(), e.getMessage());
}
}
return result;
}
if any clarifications, please reply a message for this post,
THANKS
im currently trying to implement the Steam Web API using the given code in the following repository -> https://github.com/Overv/SteamWebAPI/blob/master/SteamAPISession.cs into my Android app and im getting different exceptions dependend on using the given wep api ip ( 63.228.223.110 ) or the adress ( https://api.steampowered.com/ ) itself.
my code actually looks like this in the given method when building up a connection to the web api:
private String steamRequest( String get, String post ) {
final int MAX_RETRIES = 3;
int numberOfTries = 0;
HttpsURLConnection request = null;
while(numberOfTries < MAX_RETRIES) {
if (numberOfTries != 0) {
Log.d(TAG, "Retry -> " + numberOfTries);
}
try {
request = (HttpsURLConnection) new URL("https://api.steampowered.com/" + get).openConnection(); //or 63.228.223.110/ ???
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
String host = "api.steampowered.com";
int port = 443;
int header = 0;
socketFactory.createSocket(new Socket(host, port), host, port, false);
request.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
request.setSSLSocketFactory(socketFactory);
request.setDoOutput(false);
// request.setRequestProperty("Host", "api.steampowered.com:443");
// request.setRequestProperty("Protocol-Version", "httpVersion");
request.setRequestProperty("Accept", "*/*");
request.setRequestProperty("Accept-Encoding", "gzip, deflate");
request.setRequestProperty("Accept-Language", "en-us");
request.setRequestProperty("User-Agent", "Steam 1291812 / iPhone");
request.setRequestProperty("Connection", "close");
if (post != null) {
byte[] postBytes;
try {
request.setRequestMethod("POST");
postBytes = post.getBytes("US-ASCII");
// request.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
request.setFixedLengthStreamingMode(postBytes.length);
request.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(request.getOutputStream());
out.print(post);
out.close();
// DataOutputStream requestStream = new DataOutputStream(request.getOutputStream());
//// OutputStreamWriter stream = new OutputStreamWriter(request.getOutputStream());
//// stream.write(postBytes, 0, postBytes.length);
// requestStream.write(postBytes, 0, postBytes.length);
// requestStream.close();
message++;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
int statusCode = request.getResponseCode();
InputStream is;
Log.d(TAG, "The response code of the status code is" + statusCode);
if (statusCode != 200) {
is = request.getErrorStream();
Log.d(TAG, String.valueOf(is));
}
// String src = null;
// OutputStreamWriter out = new OutputStreamWriter(request.getOutputStream());
// out.write(src);
// out.close();
Scanner inStream = new Scanner(request.getInputStream());
String response = "";
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
// String src;
// BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
// StringBuilder builder = new StringBuilder();
// while ((src = in.readLine()) != null) {
// builder.append(src);
// }
// String jsonData = builder.toString();
Log.d(TAG, response); //jsonData
// in.close();
return response; //jsonData
} catch (MalformedURLException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_LONG).show();
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (request != null) {
request.disconnect();
}
}
numberOfTries++;
}
Log.d(TAG, "Max retries reached. Giving up on connecting to Steam Web API...");
return null;
}
following exception occurs when using https://api.steampowered.com/ as url:
W/System.err﹕ java.io.FileNotFoundException: https://api.steampowered.com/ISteamOAuth2/GetTokenWithCredentials/v0001
D/OptionsFragment﹕ Failed to log in!
i've really tried and researched on those issues, but i just can't get a solution. If someone got a good hint on helping to solve these exceptions please let me know!
EDIT:
I've researched some more!
Looking up on https://partner.steamgames.com/documentation/webapi#creating the direct ip adress shouldn't be used and therefore only the DNS name itself (for further clarification look on the given link). Hence, looking up on the API interface list itself -> http://api.steampowered.com/ISteamWebAPIUtil/GetSupportedAPIList/v0001/?format=json there doesn't seem to be a given Interface with a method called ISteamOAuth2/GetTokenWithCredentials.(Or not anymore!) Only ISteamUserAuth and ISteamUserOAuth which seem to handle Authentication stuff.
I will update this post again if i should get a working connection and handling with the steam web api.
Cheers!
I want to upload files one by one just like queue. In brief suppose there are 10 files and I want to upload all files and it should be checking for network connectivity is available or not, if not then those file should be into the queue and will try to upload later. It will keep on trying till any single file in left queue. Please help me out, How can I achieve this in android.
This is the sample code that I have tried so far
final Thread thread = new Thread(){
public void run() {
try {
while(true){
ThisCaching ic = new ThisCaching(getApplicationContext());
fileToUpload = ic.getDataFromCache("audiofiles", "SELECT * FROM audiofiles WHERE STATUS = '2' OR STATUS = '3' ORDER BY rowid DESC");
if(fileToUpload != null)
{
for (int i=0; i<fileToUpload.size(); i++) {
try {
System.out.println("Current position while uploading ::> " + i);
Thread.sleep(1000);
ConstantData.selectedFile = fileToUpload.get(i).toString();
ConstantData.position = i;
if(checkConnectivity()){
new Uploading().execute();
myApplication.getHttpClient().getConnectionManager().closeExpiredConnections();
}else{
String[] status = {"STATUS"};
String[] val = {"2"};
try {
SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB();
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
}
} catch (Exception e) {
return;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
};
String line = null;
HttpClient httpClient = null;
HttpContext localContext = null;
HttpPost httpPost = null;
MultipartEntity entity = null;
HttpResponse response = null;
HttpEntity httpEntity =null;
SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB();
try {
String strArray[]={"http://myurl.com","filename",ConstantData.selectedFile,"activityType",ConstantData.activityType,"patientId",ConstantData.patientId,"caseId",ConstantData.caseId,"doctorId",ConstantData.doctorId,"clinicCode",ConstantData.clinicCode,"documentType",ConstantData.documentType,"templateId",ConstantData.templateId};
httpClient = new DefaultHttpClient();
//httpClient.getConnectionManager().r
localContext = new BasicHttpContext();
httpPost = new HttpPost(strArray[0]);
entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(ConstantData.selectedFile);
String type = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".")+1);
if(strArray.length>1)
{
for(int i=1;i<strArray.length;i=i+2)
{
if(strArray[i]!=null){
if(!strArray[i].equalsIgnoreCase("")){
// System.out.println("i) : "+i +" i+1) : "+(i+1));
Log.i(strArray[i], "::" + strArray[i+1]);
if(strArray[i].equalsIgnoreCase("filename")){
entity.addPart("filename", new FileBody(file,"audio/"+type));
}else{
entity.addPart(strArray[i], new StringBody(strArray[i+1]));
}
}
}
}
}
httpPost.setEntity(entity);
response = httpClient.execute(httpPost,localContext);// i m getting error at this line
System.out.println("Response code is ::> " +response.getStatusLine().getStatusCode());
code = response.getStatusLine().getStatusCode();
httpEntity = response.getEntity();
line = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
code=100;
e.printStackTrace();
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e) {
code=100;
e.printStackTrace();
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (IOException e) {
code=100;
e.printStackTrace();
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (Exception e) {
code=100;
e.printStackTrace();
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
}finally{
//
try {
// System.out.println("&&&& while realeasing connection");
//// if(httpClient != null){
//// httpClient.getConnectionManager().releaseConnection((ManagedClientConnection) httpClient.getConnectionManager(), -1, TimeUnit.MINUTES);
//// }
// if(httpPost.getEntity().getContent() != null){
// InputStream content = httpPost.getEntity().getContent();
// content.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
}
return line;
`
From what I see, do you use plain Threads (cant see the edit, yet). Since Java 1.5 there's an package for such things as queues and mutlithreading, that makes live much easier.
For your purpose of a queue, you can create a single threaded executor with Executors.newSingleThreadExecutor(). You get a Threadpool with just one thread that executes each task you submit(Runnable) in the order you submitted them. Java garanties, that the Executor always has one thread working on the queue (Java recreates the Thread automatically if it dies)
Each task you submit implements a Runnable. So, to implement the three retries you described, you just need a class that implements the Runnable interface, that counts the retries and - if the upload was not succesful - it increments the counter and resubmits itself.
Here's the Guide, Tutorial and Reference to Executors and ExecutorService.