Android Quickly Find All Local Devices on Network - android

I'm making an Android app that needs to be able to see local network devices (either names or ip's). Currently I can scan the network and find the local IP's of devices. However it takes so long the user sees a black screen loading for a couple minutes while it searches the network.
Here is the code that I'm currently using:
private ArrayList<String> scanSubNet(String subnet) {
ArrayList<String> hosts = new ArrayList<String>();
InetAddress inetAddress = null;
for (int i = 1; i < 100; i++) {
try {
inetAddress = InetAddress.getByName(subnet + String.valueOf(i));
if (inetAddress.isReachable(1000)) {
hosts.add(inetAddress.getHostName());
Log.d("ERRORID", inetAddress.getHostName());
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return hosts;
}
There has to be a faster way to search for network for devices right?

Please check Using Network Service Discovery and perform task in AsyncTask. Keep on updating the UI when a new node joins your local network.

Related

Apps did not download after vpn is connected

I am making an application that block certain webs and application but problem is on Some devices manufacture Like Motorola and HTC (android OS nougat and oreo) apps did not download and update after VPN is Connected But Internet Work perfectly.I am using Local VPN to monitor Network Trafic. Please Help i am stuck on this stage.
I tried all methods mention on the google
https://www.androidpit.com/google-play-not-working
http://appslova.com/android-fix-error-495-in-google-play-store/
http://techknowzone.com/how-to-solve-fix-error-code-495-in-google-play-store/
Below is the Snipped of local VPN Code
private void connect() {
int i;
isRunning=true;
Builder builder = new Builder();
StringBuilder stringBuilder = new StringBuilder("10.0.0.");
if (lastInt == 254) {
i = 0;
lastInt = 0;
} else {
i = lastInt;
lastInt = i + 1;
}
this.localAddress = stringBuilder.append(i).toString();
try {
if (this.parcelFileDescriptor != null) {
this.parcelFileDescriptor.close();
}
} catch (Exception e) {
}
try {
builder.addAddress(this.localAddress, 24);
builder.addDnsServer(dns1);
builder.addDnsServer(dns2);
this.parcelFileDescriptor = builder.setSession(getString(R.string.app_name)).setConfigureIntent(this.pendingIntent).establish();
Intent intent = new Intent("STARTEDDNSCHANGER");
intent.setAction(getPackageName() + ".STARTED_DNS_CHANGER");
sendBroadcast(intent);
} catch (Throwable e2) {
throw new IllegalArgumentException(e2);
}
}
Play downloads apps over HTTPS. If you are getting error 495 it suggests that the VPN is interfering with the HTTPS / TLS handshaking, and so Play won't download the apps. Possibly you don't support the cipher algorithm negotiation properly.

android can not connect to MySql

When I connect to MySQL in android:
code show as below
protected static void connMysql(){
Connection conn = null;
PreparedStatement pstm = null;
ResultSet res = null;
String openurl_mysql="jdbc:mysql://10.15.26.21:3306/etrack_user&autoReconnect=true&failOverReadOnly=false";
try {
java.sql.Driver.class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(openurl_mysql,"etrack","_etrack_mysql_");
pstm = conn.prepareStatement("select count(*) as count from et_patrol_task");
res = pstm.executeQuery();
while(res.next()){
int count = res.getInt("count");
System.out.println("return success=============="+count);
}
res.close();
pstm.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
When I run the program,I get the following problem:enter image description here
Has anyone encountered a similar problem or solved it?
You can't access a MySQL DB from Android natively.Actually you may be able to use JDBC, but it is not recommended.
JDBC is infrequently used on Android, and I certainly would not recommend it.
IMHO, JDBC is designed for high-bandwidth, low-latency, highly-reliable network connections (e.g., desktop to database server, Web application server to database server). Mobile devices offer little of these, and none of them consistently.

can't ping the same IP twice

I have written this code for pinging class C IP addresses on port 6789, the thread starts when I click on a button called PING. It will retrieve all IP addresses that has the port 6789 open. But what I need is to refresh (re-ping) every, let's say 5 seconds, and add IPs recently joined if exist and omit ones that leave the port. Unfortunately another issue appears. When I started the application the first iteration of the while (true) works perfectly, and it adds any IP that had the port 6789 open to the ArrayList ips_List and then display it on the ListView, and when another device joins the port, my phone will add it to the ips_List also. BUT in the second iteration after the Thread sleeps 5 seconds and then begins to re-ping the IPs from (x.x.x.1 - x.x.x.254) to see if another IP had joined the port when pinging to an IP previously pinged, the Socket will throw IOException (as written in the code).
Why is that happening?
Thread pingo = new Thread(new Runnable() {
public void run() {
while (true) {
if (readableNetmask.equals("255.255.255.0")) {
for (int i = 2; i <= 25; i++) {
String ip_address = readableIPAddress;
String oct1 = "", oct2 = "", oct3 = "", oct4 = "";
StringTokenizer stok = new StringTokenizer(
ip_address, ".");
while (stok.hasMoreTokens()) {
oct1 = stok.nextToken();
oct2 = stok.nextToken();
oct3 = stok.nextToken();
oct4 = stok.nextToken();
}
to_ping_ip = oct1 + "." + oct2 + "." + oct3
+ "." + String.valueOf(i);
if (pingAddress(to_ping_ip, 6789)) {
ips_List.add(to_ping_ip);
}
}
}
// delay 10 seconds, then re-ping
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
break;
}
handler.post(new UpdateIPListViewRunnable());
}
}
});
pingo.start();
PingAddress() function:
public boolean pingAddress(String ip, int port) {
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(ip, port), 200);
socket.close();
} catch (IOException e) {
return false;
}
return true;
}
List where addresses appear:
static public class UpdateIPListViewRunnable implements Runnable {
public void run() {
arrayAdapter.clear();
for (int i = 0; i < ips_List.size(); i++) {
arrayAdapter.add(ips_List.get(i));
arrayAdapter.notifyDataSetChanged();
}
ips_List.clear();
}
}
Your problem is likely in your atypical usage of the word "ping". Traditionally, this refers to sending an ICMP echo request, which does not involve connection state, but is also often not allowed to ordinary user IDs such as your application will run under.
You appear to be using a stateful TCP connection instead, and may be running into difficulty in if your server is not tuned to be able to accept rapid reconnects. So you may want to try testing your server using some other client. You could also have a problem in that TCP will keep trying to get the traffic through, so it won't quickly report network troubles. You may even be ending up with multiple attempts overlapping in time.
Your best solution though would probably be to switch from TCP, which is ill suited to this task, to UDP, which is probably a better match. UDP does not have connection state, and it's also unreliable in that no automatic retries are attempted. You should be able to find a UDB echo server and client type example with a web search.
Thank you #Chris Stratton ... and there is noway that I am changing to protocol to UDP since my project's structure is build over the TCP architecture ... now for my problem I finally FOUND the solution; in my app i have a ServerSocket that is used for pinging ... now considering there are two mobiles with the same app, if PING button clicked then it will ping the other device and and the other device will accept() the connection then close() it. Now on the first mobile it will iterates another time (while(true)) and ping the same device, but that device has the ServerSocket closed so it will returns false. For this is used a recursive thread that when a mobile 1 pings mobile 2, mobile 2 will close the ServerSocket and immediately calls the same thread so the ServerSocket is opened to other pings. I tried it and it worked very well :DDD
[#Experts: any enhancements for this solution!]
Recursive Thread:
static public class ReceivePingThread extends Thread {
public void run() {
try {
ServerSocket joinPort = new ServerSocket(6789, 100);
joinPort.accept();
joinPort.close();
ReceivePingThread ReceivePingThread = new ReceivePingThread();
ReceivePingThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Android 4.0+ Bluetooth connection error to an embedded device: "Permission Denied"

I have the following setup:
An Android device uses a 'Client' socket to connect to a remote embedded device, The Android application uses the following code snippet to connect to the embedded device.
On the embedded device uses MindTree BT stack, where server serial socket is prepared according to some properties in the device, which the Android application is familiar with, the connection defined on the embedded device, is not secured!!
The combination of both applications works on:
2 LG phones different models (version code < 10 uses the "Normal method")
2 HTC's different models (version code < 10 uses the "Workaround method")
Pantech Tablet (version code < 13 uses the "Workaround method")
Today, I've tried the application on Samsung S3, Motorola MB886, and a Nexus 7...
All resulted in a "Permission Denied" when calling to socket.connect()... (I have the proper permissions in the manifest, otherwise it would not work on the other devices.)
All the new devices I've tested on are version code > 4.0, so I'm wondering:
Does anyone know about any changes in the API?
Perhaps Android 4.0+ forces security?
It seem that the error occur in the Bonding state, since I can see on the embedded program logs...
Any insights?
The code:
public final synchronized int connectToDevice(int connectingMethod)
throws BluetoohConnectionException {
if (socket != null)
throw new BadImplementationException("Error socket is not null!!");
connecting = true;
logInfo("+---+ Connecting to device...");
try {
lastException = null;
lastPacket = null;
if (connectingMethod == BluetoothModule.BT_StandardConnection
|| connectingMethod == BluetoothModule.BT_ConnectionTBD)
try {
socket = fetchBT_Socket_Normal();
connectToSocket(socket);
listenForIncomingSPP_Packets();
onConnetionEstablished();
return BluetoothModule.BT_StandardConnection;
} catch (BluetoohConnectionException e) {
socket = null;
if (connectingMethod == BluetoothModule.BT_StandardConnection) {
throw e;
}
logWarning("Error creating socket!", e);
}
if (connectingMethod == BluetoothModule.BT_ReflectiveConnection
|| connectingMethod == BluetoothModule.BT_ConnectionTBD)
try {
socket = fetchBT_Socket_Reflection(1);
connectToSocket(socket);
listenForIncomingSPP_Packets();
onConnetionEstablished();
return BluetoothModule.BT_ReflectiveConnection;
} catch (BluetoohConnectionException e) {
socket = null;
if (connectingMethod == BluetoothModule.BT_ReflectiveConnection) {
throw e;
}
logWarning("Error creating socket!", e);
}
throw new BluetoohConnectionException("Error creating RFcomm socket for BT Device:" + this
+ "\n BAD connectingMethod==" + connectingMethod);
} finally {
connecting = false;
}
}
protected void onConnetionEstablished() {
logInfo("+---+ Connection established");
}
private synchronized void listenForIncomingSPP_Packets() {
if (socketListeningThread != null)
throw new BadImplementationException("Already lisening on Socket for BT Device" + this);
logInfo("+---+ Listening for incoming packets");
socketListeningThread = new Thread(socketListener, "Packet Listener - " + bluetoothDevice.getName());
socketListeningThread.start();
}
private BluetoothSocket fetchBT_Socket_Normal()
throws BluetoohConnectionException {
try {
logInfo("+---+ Fetching BT RFcomm Socket standard for UUID: " + uuid + "...");
return bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
} catch (Exception e) {
throw new BluetoohConnectionException("Error Fetching BT RFcomm Socket!", e);
}
}
private BluetoothSocket fetchBT_Socket_Reflection(int connectionIndex)
throws BluetoohConnectionException {
Method m;
try {
logInfo("+---+ Fetching BT RFcomm Socket workaround index " + connectionIndex + "...");
m = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
return (BluetoothSocket) m.invoke(bluetoothDevice, connectionIndex);
} catch (Exception e) {
throw new BluetoohConnectionException("Error Fetching BT RFcomm Socket!", e);
}
}
private void connectToSocket(BluetoothSocket socket)
throws BluetoohConnectionException {
try {
logInfo("+---+ Connecting to socket...");
socket.connect();
logInfo("+---+ Connected to socket");
} catch (IOException e) {
try {
socket.close();
} catch (IOException e1) {
logError("Error while closing socket", e1);
} finally {
socket = null;
}
throw new BluetoohConnectionException("Error connecting to socket with Device" + this, e);
}
}
After very long long time of investigating the matter I've found one reason for the error... on some Android devices the auto Bluetooth peering is not enabled/allowed.
So, apparently except for two connection method, there are also two Bluetooth adapter enabling method, one would be to throw an intent to ask the system to turn the adapter on, and the other is to call onto the BluetoothAdapter.enable() method, which enables the Bluetooth silently.
The first method, pops a confirmation dialog, and require user interaction while the other does not, and while not showing the Bluetooth enabling confirmation dialog, also the peering confirmation is not shown, which causes the connection error.
Using the first adapter enabling method solves the problem on most of the devices, like the Nexus 7, Samsung S3, and a few others, but on some devices there is still an issue, and I'm not really sure why, but this is much better since many devices are now working with the new implementation.

getSocketAddress() method causes delay which leads to communication lag in Android

I'm developing a UDP responder to handle basic SSDP commands. The purpose of this piece of code is to do auto discovery, so when the server sends a multicast to a specific group all other subscribed devices should send back a UDP packet announcing its presence to the host and port of who sent the multicast. My android device receives and sends the packet just fine but because it takes too long to get back the SocketAddress object from getSocketAddress() method the server times out, closes the listening port and never gets a packet back from the android device.
Here's my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MulticastSocket ms = null;
byte[] packBuf = new byte[128];
try {
ms = new MulticastSocket(32410);
ms.joinGroup(InetAddress.getByName("239.255.255.250"));
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
while (true)
{
DatagramPacket receivedPack = new DatagramPacket(packBuf, packBuf.length);
try {
ms.receive(receivedPack);
Log.d(TAG, "Received data");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
String responseStr = "HTTP/1.0 200 OK\n" +
"Content-Type: app\n" +
"Resource-Identifier: 945e7dd5913ab45f1db4f271a1620b9471fb7d4d\n" +
"Name: Test App\n" +
"Port: 8888\n" +
"Updated-At: 1319511680\n" +
"Version: 0.9.3.4-29679ad\n" +
"Content-Length: 23\n\n" +
"<message>test</message>";
byte[] response = responseStr.getBytes();
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
} catch (IOException e2) {
// TODO Auto-generated catch block
Log.e(TAG,"Erro",e2);
}
DatagramPacket outPack;
try {
outPack = new DatagramPacket(response, responseStr.length(), receivedPack.getSocketAddress());
sendSocket.send(outPack);
} catch (UnknownHostException e1) {
Log.e(TAG,"Erro",e1);
}
catch (IOException e) {
Log.e(TAG,"Erro",e);
}
catch (Exception e)
{
Log.e(TAG,"Erro",e);
}
}
}
Any ideas?
thanks in advance,
fbr
The most likely problem is that getSocketAddress() is trying to resolve the DNS name of the IP address, which is timing out either due to it being a multicast address or just general DNS lag.
The InetSocketAddress class has a constructor option needResolved which can control this behavior. Unfortunately, it does not appear that DatagramPacket.getSocketAddress() allows you to specify that you want that set to false.
This is apparently a known issue, with some recent discussion of it here:
Issue 12328: DatagramChannel - cannot receive without a hostname lookup
The thread suggests that this has been fixed in Android 3.0, and offers a couple of workarounds for Android 2.0 which may or may not work.
In your case, you could try creating an InetSocketAddress set to INADDR_ANY and port 0 with needsResolved set to 0, and then pass that in when you create receivedPack. Hopefully receive() will reuse that and remember the setting.
2 things come to mind...
1) What happens when you change:
outPack = new DatagramPacket(response, responseStr.length(), receivedPack.getSocketAddress());
to
outPack = new DatagramPacket(response, responseStr.length(), receivedPack.getAddress(), receivedPack.getPort());
2) I remember having this sort of problem with an embedded Java on a Home Automation system. Our short term solution was to put most of the machine and multicast addresses in the hosts file. Long term we ended up with a local DNS server.
There is a parameter somewhere in the Java Network stack that tells it how long to cache DNS failures in memory. We cranked that number up to, I think, 5 minutes instead of 10 seconds.

Categories

Resources