Android - Ethernet - Programmatically - android

I am developing an Android app which will be used by custom devices which will have ethernet support (and also wifi).
The app has to enable a settings activity for Ethernet.
Please NOTE that these settings have to be run by the app and not by the Android settings, since the app will be the only thing running on the device and the user will not have access to the Android running in the background.
The user has to be able to:
ENABLE/DISABLE Ethernet
Choose DHCP or STATIC
If choosing STATIC - set IP, gateway
The problem is that I cannot access the android.net.ethernet programmatically and there is no explanation about this issue online.
So if someone has done something like this, please help me get into the right direction.

I know it is very late but it might help someone else.
I had some of the requirements you mentioned for my android application.
This is how I achieved some of the points
1. ENABLE/DISABLE Ethernet
//Enable Ethernet
ifconfig eth0 up
//Disable Ethernet
ifconfig eth0 down
3. If chosen STATIC - set IP, gateway
Fire these commands from java code.
su -c ifconfig eth0 172.19.10.105 netmask 255.255.255.0 up
route add default gw 172.19.10.2 dev eth0
You can execute these commands using following code.
Here command variable is one of the commands mentioned above.
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "n");
}
} catch (Exception e) {
e.printStackTrace();
}
String response = output.toString();

Related

Permission Denied for access /proc/net/arp ARP table in Android 10

Using ARP table we can access IP and MAC of hotspot connected devices in Android 9 and earlier versions. Now from Android 10 permission denied for the same. Kindly suggest how can I access IP and MAC address of connected devices in Android 10. Below Code working in up-to Android 9 Version but not work in Android 10.
BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] clientInfo = line.split(" +");
if(!clientInfo[3].equalsIgnoreCase("type")) {
String mac = clientInfo[3];
String ip = clientInfo[0];
textView.append("\n\nip: " + ip + " Mac: " + mac);
Log.d("IP : ", ip);
Log.d("Mac : ", mac);
}
}
Run the ip neigh show command and process its output:
val runtime = Runtime.getRuntime()
val proc = runtime.exec("ip neigh show")
proc.waitFor()
val reader = BufferedReader(InputStreamReader(proc.inputStream))
You split the lines the same way, IP is [0], MAC is [4].
Android 10 introduces several privacy-related restrictions that disallow apps to access certain information that could be potentially misused for fingerprinting and data collection. One of among them is the restriction on access to /proc/net filesystem on devices that run Android 10 or higher, apps cannot access /proc/net, which includes information about a device's network state. Apps that need access to this information, such as VPNs, should use the NetworkStatsManager or ConnectivityManager class.
The current APIs in Android doesn't allow apps to access the ARP cache. I see a bug is raised in Google issue tracker that is currently in the below status - https://issuetracker.google.com/issues/130103885
Status: Won't Fix (Infeasible) We've passed along your input to our
internal teams, who are evaluating it for a future release. We're
closing this issue for now, and thanks for sending us your feedback!"
https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem
Related thread [ Acccess to /proc/net/tcp in Android Q ] - https://stackoverflow.com/a/58501039/4694013

How to open / get available drivers from a USB device connected to Android?

I made a similar post about how I can best send data to and receive data from a USB device connected to Android using the native API. Someone turned me toward a library for serial communication, so I'm trying to understand how to use that.
I'm only using some of the example code so far just to see something working, but I'm stuck on trying to open the USB device. Here's a verbose print out of the USB device I'm using. It's a CDC device that should echo back what is sent to it.
Here's that code I have running right now. The app has a single button that does this function.
private void DoTheThing () {
String textMessage = "";
// Find all available drivers from attached devices.
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
if (availableDrivers.isEmpty()) {
textMessage += "Could not find any avaliable drivers.\n";
m_textView.setText(textMessage);
return;
}
// Open a connection to the first available driver.
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
if (connection == null) {
// add UsbManager.requestPermission(driver.getDevice(), ..) handling here
textMessage += "Could not open device.\n";
m_textView.setText(textMessage);
return;
}
UsbSerialPort port = driver.getPorts().get(0); // Most devices have just one port (port 0)
try {
port.open(connection);
port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
} catch (IOException e) {
textMessage += e + "\n";
m_textView.setText(textMessage);
return;
}
textMessage += "I did the thing.\n";
m_textView.setText(textMessage);
}
The function stops at the first return where an available driver can not be found.
I was having a similar issue before where the native API was failing at opening the device. This library is failing to find an available driver.
I'm testing on a Pixel 3. Could the Pixel it self be lock down the device before I can run my app? I plug the Pixel into my desktop and then 'run app' from Android Studio (I have USB Debugging on and dev options enabled). Once the app is running, then I unplug it from the desktop and plug in my USB device. Could this be altering the state in a weird way?
EDIT:
Got it working with adding permissions.
PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
manager.requestPermission(driver.getDevice(), usbPermissionIntent);
for CDC devices you usually have to provide a customProber for your VID:PID or use a hardcoded driver. The next issue you will ver likely run into, is missing privilege handling.

Cannot connect to sqlserver when my android phone is connected to pc thorugh usb

I have been facing a problem from few days. I have created an android app which has a button. When button is clicked it should fetch data from sql server. I have given my IP for the connection string i.e. 192.168.x.x, this app is running successfully on emulator. But when i run the app from the samsung galaxy phone is does not get connected to sql server. This question has been posted many times and i have done lot of research on it but could not find proper answer. I m confused with connection string. Should i use 10.0.2.2 or 127.0.1.1 or my static ip. Thanks in advance for help. I will be grateful for the replies i get. Please do help me !!!
Depending on your phone USB connection is used to :
-Share phone connection with computer
-transfer some informations between the phone and the computer
...
But to connect to your sql server ( hosted in the computer ) you must have the two devices computer and phone on the same network
What you are doing is trying to connect over the wifi network by 192.168.x.x
Check you network properties to see what's the ip for your computer in the USB-phone-computer network not in the wifi network
This is my code which i m using. I have a database SysTestNew. I am importing parties from the table and adding them in my sqlite database. I m calling the importdata() on my button. This works well in emulator but not on my samsung phone.
String userName = "xxxxxx";
String password = "xxxxx";
String url = "jdbc:jtds:sqlserver://192.168.x.x:1433/SysTestNEW";
Connection conn;
String ACCODE, ACC_DESC, Address, Phone, Mobile, Area_Code, AREA_DESC,
ItemCode, ItemDesc, itemgroup_code, ITEMSUBGRP, unit, SaleRate,
getsalesmanname, getareaval, getgrpval;
DatabaseOperations db = new DatabaseOperations(this);
Button btnback, btnimport, btnimportitem;
Spinner spinareaname, spinitemname;
CheckBox chkareaall, chkitemall;
public void importdata() {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
Toast.makeText(getApplicationContext(), "Connection open",
Toast.LENGTH_LONG).show();
Statement stmt = conn.createStatement();
ResultSet reset;
if (!chkareaall.isChecked()) {
getareaval = spinareaname.getSelectedItem().toString();
reset = stmt
.executeQuery("select am.ACCODE,am.ACC_DESC,cm.Address,cm.Phone,cm.Mobile,cm.Area_Code,ar.AREA_DESC from ACCMASTER am left join Custmaster cm on am.ACCODE=cm.Accode left join AREA ar on cm.Area_Code = ar.AREA_CODE where am.GROUP_ID='DR' and ar.AREA_DESC='"
+ getareaval + "'");
} else {
reset = stmt
.executeQuery("select am.ACCODE,am.ACC_DESC,cm.Address,cm.Phone,cm.Mobile,cm.Area_Code,ar.AREA_DESC from ACCMASTER am left join Custmaster cm on am.ACCODE=cm.Accode left join AREA ar on cm.Area_Code = ar.AREA_CODE where am.GROUP_ID='DR'");
}
if (reset != null) {
while (reset.next()) {
ACCODE = reset.getString(1);
ACC_DESC = reset.getString(2);
Address = reset.getString(3);
Phone = reset.getString(4);
Mobile = reset.getString(5);
Area_Code = reset.getString(6);
AREA_DESC = reset.getString(7);
db.insertCustomer(ACCODE, ACC_DESC, Address, Phone, Mobile,
Area_Code, AREA_DESC);
}
alertdialogbox("Import Parties",
"Parties Imported Successfully !!");
}
conn.close();
} catch (Exception e1) {
e1.getMessage();
}
}
My phone has a setting as "USB Tethering". I read somewhere that this setting is used when you want to connect your phone with your pc via wifi. I enabled this setting and then run my app but got no results... Is this setting or any other setting playing a role in connecting my phone to pc's wifi??
Add import android.util.Log; to the top of your code and change the line in your catch statement from e1.getMessage(); to Log.e("DBDebug", e1.getMessage());
Then run this code on the phone again with the USB cable attached. If you are using the ADT with eclipse, add a tag filter to the logcat window as "DBDebug". This will show all of the debugging messages for your app and will catch any error messages. Look through that and see if there's any errors reported from jdbc.
Or, if you're using the android tools from the console, the command is adb logcat -s "DBDebug"
It is possible to create a network between an android device and PC using the USB cable, but that is a lot more complicated than just using the pre-existing network that is already working by connecting your phone to the WiFi.
On the computer that the SQL server is running, open a command window/console and type 'ipconfig'. You will see something similar to this. The line reading IPv4 address is the IP address your android application will use to connect to the SQL server.
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::e4f4:7f27:bb97:ac87%10
IPv4 Address. . . . . . . . . . . : 192.168.0.7
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.0.1
You will also need to ensure there is no firewall blocking connections over the network to your SQL server.
Depending on how your SQL server is set up, it may only allow access from localhost rather than across the network. Ensure that you have configured a user within the SQL server and aren't trying to connect as the root user. Default SQL users often only allow localhost connections for security reasons. I believe this could be what your problem is, you need to create a user that is able to access the server over the network.
If you are using MySQL the syntax would be something similar to this:
CREATE USER 'david'#'192.168.0.0/255.255.255.0';
If for example your network is in the 192.168.1.xxx range, you would change the above line to reflect that.

Connecting Android with PC and displaying a message

I am new to android. I am just trying to connect my Android device to PC and pass a string to PC using Bluetooth. I have no idea on how to do it. Android side I read about the Bluetooth API. Please suggest me some ways to do it. Thanks in advance.
For Android, my code is slightly different from yours:
BluetoothSocket socket = Device.createRfcommSocketToServiceRecord(device_UUID);
socket.connect();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeChar('x'); // for example
socket.close();
I used DataOutputStream to send data to PC. But surely this doesn't matter, just for your reference.
For PC,
LocalDevice localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC); // Advertising the service
String url = "btspp://localhost:" + device_UUID + ";name=BlueToothServer";
StreamConnectionNotifier server = (StreamConnectionNotifier) Connector.open(url);
StreamConnection connection = server.acceptAndOpen(); // Wait until client connects
//=== At this point, two devices should be connected ===//
DataInputStream dis = connection.openDataInputStream();
char c;
while (true) {
c = dis.readChar();
if (c == 'x')
break;
}
connection.close();
I am not sure if the above codes still work today, as this was done 2 years ago. The BlueCove API may have changed a lot. But anyway, these codes work for me. Hope this may help you.
One more note is that, I had to uninstall the Toshiba Bluetooth Driver in my PC and reinstall the Microsoft one in order to make use of BlueCove. Otherwise, it won't work. (However, latest version of BlueCove may have already supported different drivers, please correct me if I said anything wrong.)
(Author: Victor Wong)
For clarification: on the PC side, you usually have a bluetooth device that comes with a virtual COM port. For testing purposes, you can use any terminal program (e.g. http://realterm.sourceforge.net/). When you start it on your virtual bluetooth serial port and connect your Android device, it will show the received data.

Android Strange bluetooth issue either in API or i m missing something

My problem is that i am not able to find the class of device and device services of my own bluetooth device. Though i am able to find the Connection State, MAC address and other info using the
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
I even tried accessing the Bluetooth folder in sys>devices>virtual path but this folder is not located in every device.
Could there be any way to fetch the bluetooth info by accessing the proc file system, if yes please help.
It is really strange that i am able to the bluetooth class of remote devices by fetching the
btAdapter.getBondedDevices();//Retruns the set of BluetoothDevice class
but i am not able to get device class of default(own) bluetooth.
Finally after a lot of struggling i found a way to find the services 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

Categories

Resources