Detecting android devices connected to Wifi - android

I want to make an android application that connects to a Wifi network, say network SSID = "ABC".Assume that it is connected to the Wifi ABC. After connecting to ABC, i would want my application to display the ips of all the android devices that are connected to the same wifi ABC network. How can i achieve that? Thanks

Check out the file: /proc/net/arp on your phone.
It has the ip and MAC addreses of all the other devices connected to the same network. However I am affraid you wont be able to differentiate if they are android phones or not.

You will want to use tcpdump to put the network card into promiscous mode and then capture packets to identify what other clients are on your network.
How to use tcpdump on android:
http://source.android.com/porting/tcpdump.html
You can run commands in your code like so:
try {
// Executes the command.
Process process = Runtime.getRuntime().exec("/system/bin/ls /sdcard");
// Reads stdout.
// NOTE: You can write to stdin of the command using
// process.getOutputStream().
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
return output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

Related

How to make an android app to get the IP address of the pc from my android device connected on same wifi

I want to make an android app to find the IP address of all the connected devices connected on the same wifi. I tried this :
for (int i = lower; i <= upper; i++) {
String host = subnet + i;
try {
InetAddress inetAddress = InetAddress.getByName(host);
if (inetAddress.isReachable(timeout)){
publishProgress(inetAddress.toString());
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
But it can get only the connected mobile phone's IP, not the pc's.
How to get the connected pc's IP address also?
Try this
public ArrayList<String> getClientList() {
ArrayList<String> clientList = new ArrayList<>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] clientInfo = line.split(" +");
String mac = clientInfo[3];
if (mac.matches("..:..:..:..:..:..")) { // To make sure its not the title
clientList.add(clientInfo[0]);
}
}
} catch (java.io.IOException aE) {
aE.printStackTrace();
return null;
}
return clientList;
}
and use it like this
ArrayList<String> list = getClientList();
for (String ip:list) {
Log.e(TAG,ip);
}
Result :
192.168.1.9
192.168.1.1
192.168.1.5
also check this question
Many networks ban that entirely, a practice known as "wireless isolation" or "client isolation", which saves battery, improves throughput, improves privacy if the network is public, at a cost of making it difficult for one client to find other hosts on the same WLAN.
For the remaining ones, pinging all of the addresses in the subnet will generally be the best way, even if a little slow. Your code looks okay, provided that the string subnet ends with a dot.
All of this is meaningless on IPv6, of course.

Not able to read InputStream from RS232 Bluetooth module

I am trying to read values from a weighing machine connected to bluetooth module(M143 RS232 Bluetooth Serial Adapter purchased from eBay).I am able to connect the device and i am getting Socket object.But the InputStream is blocking and not able to read data from the stream(inputstream.available() is always returns zero).There is no issue when i write something to the OutputStream.I tried using BufferedReader but no change.Following is the code i tried.
InputStream inputStream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
//code is not reaching here it is blocking in the while loop
if(outputStream!=null){
outputStream.flush();
outputStream.close();
}
Are you opening sockets for connection in different threads. There should be 3 threads for connection. This is valid for non-Bluetooth LE. Bluetooth Connectitivty
Connection Thread
Accept Thread
Connected Thread
If you use these threads, you will be able to get data using connected thread and you can pass data to main thread using handler, callback or BroadcastReceiver. I use all three of them seamlessly.
If you wish to check whether it works or not, download Bluetooth Terminal app from Play Store. It exactly uses Threads and Handler to display data. You can find one of the Bluetooth Terminal source code too. One of them is open source.
For BLE you can try this link. There are working samples associated with guides.
If you want to be sure your BT device works, download a BT terminal program pc or/and Android and test your device.
It is important to note that .read() or .readline() only halts reading when there is a newline or EOF, end of file.
However, socket connection does not have EOF unless the socket transfer is done.
so you could do the two following cases:
1) Change the other side(weighing machine in your case) to add \n or \r after each data transfer to let the Android side know one full set of data was sent.
This keeps the benefit of socket connection.
and you could do
while ((line = r.readLine()) != null) {
//do what you want to do with line
//... you dont need string builder in this case
}
2) Halt each connection from the other side after each data transfer. This is not recommended because it is not anymore a socket transfer when you cut after every data transfer. Also it might cause TIME_WAIT and hinder further connections.
I was able to do the first case to solve my problem when I was in your shoes.
The execution blocking in reading of InputStream is because of if no bytes are coming from the Socket,the existing thread will wait for a byte to come from the Socket.
Communication via bluetooth with other android devices or microcontrollers such as Arduino Android Smooth Bluetooth
// This thread runs during a connection with a remote device.
// It handles all incoming and outgoing transmissions.
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}

Detecting all devices connected to my wifi router using Android Programming

I am trying to build an app in Android that would need the IP addresses of all devices (PCs and other mobile devices) connected to a wifi router (my local router). The IP addresses are the ones assigned to the devices by the router using DHCP. Moreover, the app that I am trying to build would be local to a device connected to the same router. I have looked all over the web for Android code that could accomplish this, but all I found was how to scan for wifi access-points. Is what I am trying to do possible using Android programming?
There's no direct API for this. Its not like the wifi router gives everyone a list of all IPs it assigns. You could try pinging every IP on your wifi network (you can tell what IPs those are by netmask), but that will only work if the device is configured to return ICMP packets and your router doesn't block them.
What might work for your app is Wi-fi direct (http://developer.android.com/guide/topics/connectivity/wifip2p.html).
It totally depends on your router: if it has this sort of functionality exposed via API or other. Most routers don't permit this sort of deep-querying. You might look at tomato or dd-wrt if you want to have more control over it.
You can do this by using the arp cache table by:
BufferedReader br = null;
ArrayList<String[]> ipCache = new ArrayList<>(3);
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] split = line.split(" +");
if (split.length >= 4 ) {
if(!split[0].equals("IP") &&!split[0].equals(ROUTER_IP) ){
ipCache.add(split);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
int ipsPonged = ipCache.size();
if(ipsPonged>0){
for (String[] client :
ipCache) {
// if one ping test succeeds we are fine
if(!ping(client[0])){
ipsPonged--;
}
}
if(ipsPonged == 0){
return true;
}
}else{
return false;
}

Android get UUID(Services) of own bluetooth device

I am creating a application in which one module is there where i want to retrieve the services supported by my own Bluetooth device...
Currently i am able to fetch the UUID of remote devices, by i havent found out any way to retrieve the UUID of my own device.
Thanks in advance
Finally after a lot of struggling i found a way to find the UUID of own bluetooth device. Sdptool provides the interface for performing SDP queries on Bluetooth devices, and administering a local sdpd. Code snippet for it is follows:This code will only work in devices with root access.
try {
System.setOut(new PrintStream(new FileOutputStream("/mnt/sdcard/abc.txt")));
System.out.println("HelloWorld1");
Process p;
p = Runtime.getRuntime().exec(new String[] { "su", "-c","sdptool", "browse", "local" });
BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String s;
String res = "";
while ((s = stdInput.readLine()) != null) {
if(s.contains(""))
System.out.println(s);
Log.e("above -----", s);
}
p.destroy();
return res;
} catch (Exception e) {
e.printStackTrace();
}
and in case you want to discover the services of another Bluetooth device then you can replace "local" with the MAC address of the remote device.
Or you can also try running the sdp tool usinf adb shell as follows:
adb shell sdptool browse local

Use TCP in Internet

I'am use TCP for connect my android phone with Windows 7 PC. When I'am send message phone-PC in LAN this system is work, as i`am use this system in Internet she is down because android app send me "time out". Why?
// The host name can either be a machine name, such as "java.sun.com", or a
// textual representation of its IP address
String host = "10.26.144.118";
int port = 20;
try {
Socket socket = new Socket(InetAddress.getByName(host), port);
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
// true for auto flush
writer.println("Hello World");
myView.setText("Send hello world");
} catch (Exception e) {
System.out.println("Error" + e);
myView.setText("Error" + e);
}
You are probably looking for port-forwarding
Your problem is that you mixed up the LAN (local area network) with the WAN (wide area network) aka the internet. Your personal LAN is protected from outside.
You need a static public IP or a DDNS (Dynamic DNS) solution e.g. dyndns. Than you have to forward the traffic from your public IP to you internal Server IP. See also thax's answer.
Than can your smartphone connect to your static public ip or to your DDNS address. Than should your app also work with the mobile network.

Categories

Resources