1

I am trying to do an application which works quite similar to Fing. I would like to get the IP addresses and the Mac address from all devices connected to the same network.

I tried to use a nmap command (used in Linux) but unfortunately it doesn't work. Anybody knows how could I get this information?

EDIT:

The Nmap address which I use is the following.

try {
        StringBuffer output = new StringBuffer();
        Process proc = Runtime.getRuntime().exec("sudo nmap -sP 192.168.1.0/24");
        proc.waitFor();
         BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
         String line = "";
         while ((line = reader.readLine())!= null) {
             output.append(line + "\n");
          }
        Log.e("RESULT",output.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

And then it throws an Exception:

07-30 17:51:55.789: W/System.err(25319): java.io.IOException: Error running exec(). Command: [sudo, nmap, -sP, 192.168.1.0/24] Working Directory: null Environment: null
07-30 17:51:55.789: W/System.err(25319):    at java.lang.ProcessManager.exec(ProcessManager.java:224)
programmer23
  • 533
  • 4
  • 15
  • Nmap has been ported to Android (https://secwiki.org/w/Nmap/Android), but isn't part of the basic Android distro. You'd have to install it yourself. There are apps that do this available in the app stores. Can you be more specific about why nmap didn't work for you? – Paul Ratazzi Jul 30 '14 at 15:34
  • I have edited the question with the part of code where I send the Nmap command. – programmer23 Jul 30 '14 at 15:51
  • possible duplicate of [How to get IP address of the device?](http://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the-device) – peko Sep 15 '15 at 18:30

1 Answers1

-1
// AndroidManifest.xml permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

// test functions
Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6 
mport java.io.*;
import java.net.*;
import java.util.*; 
import org.apache.http.conn.util.InetAddressUtils;

public class Utils {

/**
 * Convert byte array to hex string
 * @param bytes
 * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sbuf = new StringBuilder();
        for(int idx=0; idx < bytes.length; idx++) {
            int intVal = bytes[idx] & 0xff;
            if (intVal < 0x10) sbuf.append("0");
            sbuf.append(Integer.toHexString(intVal).toUpperCase());
        }
        return sbuf.toString();
    }




/**
     * Get utf8 byte array.
     * @param str
     * @return  array of NULL if error was found
         */
        public static byte[] getUTF8Bytes(String str) {
            try { return str.getBytes("UTF-8"); } catch (Exception ex) { return null; }
        }
/**
 * Load UTF8withBOM or any ansi text file.
 * @param filename
 * @return  
 * @throws java.io.IOException
     */
    public static String loadFileAsString(String filename) throws java.io.IOException {
        final int BUFLEN=1024;
        BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
            byte[] bytes = new byte[BUFLEN];
            boolean isUTF8=false;
            int read,count=0;           
            while((read=is.read(bytes)) != -1) {
                if (count==0 && bytes[0]==(byte)0xEF && bytes[1]==(byte)0xBB && bytes[2]==(byte)0xBF ) {
                    isUTF8=true;
                    baos.write(bytes, 3, read-3); // drop UTF8 bom marker
                } else {
                    baos.write(bytes, 0, read);
                }
                count+=read;
            }
            return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
        } finally {
            try{ is.close(); } catch(Exception ex){} 
        }
    }


/**
 * Returns MAC address of the given interface name.
 * @param interfaceName eth0, wlan0 or NULL=use first interface 
 * @return  mac address or empty string
     /
    public static String getMACAddress(String interfaceName) {
        try {
            List&lt;NetworkInterface&gt; interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                if (interfaceName != null) {
                    if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if (mac==null) return "";
                StringBuilder buf = new StringBuilder();
                for (int idx=0; idx&lt;mac.length; idx++)
                    buf.append(String.format("%02X:", mac[idx]));       
                if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
                return buf.toString();
            }
        } catch (Exception ex) { } // for now eat exceptions
        return "";
        /*try {
            // this is so Linux hack
            return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
        } catch (IOException ex) {
            return null;
        }/
    }


/**
 * Get IP address from first non-localhost interface
 * @param ipv4  true=return ipv4, false=return ipv6
 * @return  address or empty string
     */
    public static String getIPAddress(boolean useIPv4) {
        try {
            List&lt;NetworkInterface&gt; interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List&lt;InetAddress&gt; addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); 
                        if (useIPv4) {
                            if (isIPv4) 
                                return sAddr;
                        } else {
                            if (!isIPv4) {
                                int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                                return delim&lt;0 ? sAddr : sAddr.substring(0, delim);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) { } // for now eat exceptions
        return "";
    }

}

https://stackoverflow.com/a/13007325

Community
  • 1
  • 1
QArea
  • 4,955
  • 1
  • 12
  • 22