Ethernet Connectivity through Programmatically (Android) (Rooted Device)
Asked Answered
A

4

20

I have a small issue regarding Ethernet.

My three questions are:

  1. Can we programmatically Turn-On/Off Ethernet?

  2. Can we programmatically Enable/Disable Ethernet?

  3. Can we programmatically Connect Ethernet?

The above Questions are done with the Wifi. Like

  1. We can programmatically Turn-On/Off Wifi.

  2. We can programmatically Enable/Disable Wifi.

  3. We can programmatically Connect Wifi using WifiManager.

Does android provides any EthernetManager like as WifiManager to handle Ethernet?

Or, if this doesn't seem feasible, then my original requirement is:

The first thing I am going to clear is "DEVICE IS ROOTED" .

Can I manipulate the Settings (Default)? Like I don't want any other option in the Settings.apk other than WIFI and Ethernet. It should show only Wifi and Ethernet. That's it. Can I disable all the options from the Settings or Can I remove all the other options from the Settings?

Acescent answered 13/2, 2014 at 5:45 Comment(0)
D
14

The solution I will present here is a hack using reflection and does only work on a rooted android system.

Your device might have the popular android.net.ethernet package. In an Activity, try

Object emInstance = getSystemService("ethernet");

It returns an valid instance of the EthernetManager or null. Null means you are out of luck.

An additional requirement might be depending on your device: Ethernet and Wifi might only work exclusively. You might need to disable Wifi to enable Ethernet and vice versa.

To enable Ethernet by reflection use your instance of the EthernetManager. The method you want to invoke is setEthEnabled(boolean enabled)

    Class<?> emClass = null;
    try {
        emClass = Class.forName("android.net.ethernet.EthernetManager");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Object emInstance = getSystemService("ethernet");

    Method methodSetEthEnabled = null;
    try {
        methodSetEthEnabled = emClass.getMethod("setEthEnabled", Boolean.TYPE);
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    methodSetEthEnabled.setAccessible(true);
    try {
        // new Boolean(true) to enable, new Boolean(false) to disable
        methodSetEthEnabled.invoke(emInstance, new Boolean(false));
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Your application manifest needs these permissions

<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

The permission WRITE_SECURE_SETTINGS can only be acquired by system apps. The app does not need to be signed by a system key. It can be any valid sign (like the regular Android App Export function). Use busybox to remount the system partition for write access and move your apk into the /system/app folder. Reboot the device and it should work.

Can we programmatically Connect Ethernet ?

There is no Access Point to connect you like with Wifi. You either configure it for DHCP or provide static values. This can of course also be done via reflection. You will need the class EthernetDevInfo for that.

The actual implementation of the EthernetManager and EthernetDevInfo might slightly differ between Android versions and devices as it doesn't have to conform to a public api (yet) and might even be a custom version. To get a list of getters and setters you can use a Introspector or reflection in general.

Deanadeanda answered 10/4, 2014 at 9:3 Comment(4)
in my case (android 2.3) it was android.net.EthernetManager and setEthernetEnabled method. But then i get error java.lang.reflect.InvocationTargetExceptionCollapse
@Robin You are doing it all wrong. You need to cast getSystemService("ethernet") to EthernetManager. Better yet, use getSystemService(Context.ETHERNET_SERVICE) and cast that. Then you can use the proper interfaces for that manager/service.Shewchuk
@ChefPharaoh I know this is an old post but just trying to pick something up from you guys. Tried to do this in Android 11 but seems like Context.ETHERNET_SERVICE is not available anymore. Do I need to do anything in order for me to access this?Crammer
Chef Pharaoh was wrong by stating you need to use Context.ETHERNET_SERVICE instead of "ethernet". in fact both are the same. -> public static final String ETHERNET_SERVICE = "ethernet"; but the variable is hidden, so not usable by the Android public API. That's the whole sense of using reflection. To access things that are there but not exposed via public api. I personally don't have experience with this on Android 11 so I am unable to guide you there. But you might find something useful in frameworks/opt/ethernet: android.googlesource.com/platform/frameworks/opt/net/ethernetDeanadeanda
A
13

Ok here are some methods i made for manipulating with the ETHERNET INTERFACE (eth0).

1) A method for checking if an ethernet interface exists

public static boolean doesEthExist() {
        List<String> list = getListOfNetworkInterfaces();

        return list.contains("eth0");
    }

public static List<String> getListOfNetworkInterfaces() {

        List<String> list = new ArrayList<String>();

        Enumeration<NetworkInterface> nets;

        try {
            nets = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {

            e.printStackTrace();
            return null;
        }

        for (NetworkInterface netint : Collections.list(nets)) {

            list.add(netint.getName());
        }

        return list;

    }

2) A method for checking if the ETHERNET is enabled or ON

public static boolean isEthOn() {

        try {

            String line;
            boolean r = false;

            Process p = Runtime.getRuntime().exec("netcfg");

            BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream()));   
            while ((line = input.readLine()) != null) {   

                if(line.contains("eth0")){
                    if(line.contains("UP")){
                        r=true;
                    }
                    else{
                        r=false;
                    }
                }
            }   
            input.close();

            Log.e("OLE","isEthOn: "+r);
            return r; 

        } catch (IOException e) {
            Log.e("OLE","Runtime Error: "+e.getMessage());
            e.printStackTrace();
            return false;
        }

    }

3) A method for enabling or disabling the Ethernet depending on the state in which it is

public static void turnEthOnOrOff() {

        try {

            if(isEthOn()){
                Runtime.getRuntime().exec("ifconfig eth0 down");

            }
            else{
                Runtime.getRuntime().exec("ifconfig eth0 up");
            }

        } catch (IOException e) {
            Log.e("OLE","Runtime Error: "+e.getMessage());
            e.printStackTrace();
        }
    }

4) A method for connecting via ethernet depending on the chosen type (dhcp/static)

private boolean connectToStaticSettingsViaIfconfig(StaticConnectionSettings scs) {


        try {

            if(typeChosen.equalsIgnoreCase("dhcp")){

                Runtime.getRuntime().exec("ifconfig eth0 dhcp start");
            }
            else{

                Runtime.getRuntime().exec("ifconfig eth0 "+scs.getIp()+" netmask "+scs.getNetmask()+" gw "+scs.getGateway());
            }

        } catch (IOException e) {
            Log.e("OLE","Runtime Error: "+e.getMessage());
            e.printStackTrace();
            return false;
        }

        return true;
    }

There is one more class which i created for storing all the eth values needed. This class is than initialized with the values the user inserts.

public class StaticConnectionSettings {

    private String ip, netmask, dns, mac, gateway, type;

//Getters and Setters
}

This is it ... I will test it shortly... This code lacks a test phase (ping). And maybe it needs setting of DNS. But this can be done easily. I have not included it because i think on our device it will work also without the DNS setting.

Ainsley answered 17/2, 2014 at 22:28 Comment(5)
In my experience: 1) ifconfig eth0 down does not work, Android automatically puts the interface up again, and 2) ifconfig eth0 dhcp start does not work either.Chitterlings
No. ifconfig not working in my case. It works only with busybox ifconfig. Obviously, it need root privilege but I cannot assume the production device is rooted.Source
How can we send data to the Ethernet once you find out you are connected to it?Brobdingnagian
This line: Runtime.getRuntime().exec("ifconfig eth0 "+scs.getIp()+" netmask "+scs.getNetmask()+" gw "+scs.getGateway()); will possibly not work. You will need to use Super user mode to apply this method. Try: Runtime.getRuntime().exec(new String[] {"su", "-c", "ifconfig eth0 "+scs.getIp()+" netmask "+scs.getNetmask()+" gw "+scs.getGateway()});Brobdingnagian
Turning connection UP and Down are working fine but I am not able to set ip and gateways using above mensioned commands. It keeps throwing errors.Glamour
A
2

Three Answeres to your above questions:

  1. Yes. You could try using ifconfig eth0 down ; ifconfig eth0 up. But i have not tested it by myself yet.
  2. Yes, but you do not have to. Android does the switching for you. If you connect to WiFi, Ethernet disables. If you are already connected to WiFi and you plug your ethernet cable into the device; you need only to disable WiFi (which you know how to) and android switches automatically to ethernet.
  3. Not so easy as you may think. I have the same problem and until now i have found only one solution which i have not yet tested. Since android runs on the linux kernel, we can use ifconfig in order to manipulate the ethernet connection.

An explanation is hidden here: http://elinux.org/images/9/98/Dive_Into_Android_Networking-_Adding_Ethernet_Connectivity.pdf

And the youtube video of this lecture

http://www.youtube.com/watch?v=LwI2NBq7BWM

And a reference on how to use ifconfig for android

Android ethernet configure IP using dhcp

So if you come to a possible solution, please share it!! If i will do it before you i will certenly.

Ainsley answered 17/2, 2014 at 10:34 Comment(3)
Have you succeeded in doing it? I am also facing itChavira
No, sadly not :( ... sorryAinsley
Hard luck of me.. same as you.. will update here when found something usefulChavira
B
2

It works for Android 6.0.1

Class<?> ethernetManagerClass = Class.forName("android.net.ethernet.EthernetManager");

Method methodGetInstance = ethernetManagerClass.getMethod("getInstance");
Object ethernetManagerObject = methodGetInstance.invoke(ethernetManagerClass);

Method methodSetEthEnabled = ethernetManagerClass.getMethod("setEthernetEnabled", Boolean.TYPE);
methodSetEthEnabled.invoke(ethernetManagerObject, isEnabled);
Binate answered 5/11, 2018 at 14:48 Comment(1)
does this require root?Umbrella

© 2022 - 2024 — McMap. All rights reserved.