Snippets

Muhammed Ballan UtilsNetwork

Created by Muhammed Ballan
// Here i gather all Network utils that i used in many projects, i always add to it what comes up new.

// For new android SDKs, you may need to get the "InetAddressUtils.java" file into your project.

public class UtilsNetwork {

	public static String MacAddress="";

    // Generate a string which is gonna be mac addres
	private static String GenerateRandomMacAddress() {
		String[] Mac = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
		Random rd = new Random();
		rd.nextInt(15);
		String result="";

		for(int i=0;i<6;i++){
			String a = Mac[rd.nextInt(15)];
			String b = Mac[rd.nextInt(15)];
			result+=a+b;
			if(i<5){
				result+=":";
			}
		}
		return result;
	}

    // Is wifi connected to network (NOT INTERNET)
	public static boolean IsWiFiConnected(Context context) {
		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context
						.CONNECTIVITY_SERVICE);
		NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		return mWifi.isConnected();
	}

    // Is ethernet connected to network (NOT INTERNET)
	public static boolean IsLANConnected(Context context) {
		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context
						.CONNECTIVITY_SERVICE);
		NetworkInfo etherNet = connManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);

		return etherNet.isConnected();
	}

    // Changing the MAC Address to eth0 interface. needs ROOT PERMISSION
	public static boolean SetRandomMacAddress() {
		MacAddress = GenerateRandomMacAddress();
		String[] command = {"ip link set eth0 down",
						"ip link set eth0 address " + MacAddress + "",
						"ip link set eth0 up"};
		Process p;
		try {
			p = Runtime.getRuntime().exec("su");
			DataOutputStream os = new DataOutputStream(p.getOutputStream());
			for (String tmpCmd : command) {
				os.writeBytes(tmpCmd + " \n ");
			}
			os.writeBytes("exit \n ");
			os.flush();
			p.waitFor();
			return true;
		} catch (IOException e1) {
			e1.printStackTrace();
			return false;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}
	}

    // Get device's ip address. Whether it is Ethernet, wifi, or 3G.
	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
							.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
								.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
									&& (inetAddress instanceof Inet4Address)) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("EMSEM", ex.toString());
		}
		return null;
	}
    
    // Get the device's mac address of the interfaceName specified in the parameter.
    // USAGE: String etherNetMacAddres = getMACAddress("eth0"). 
    // USAGE2: String wifiNetMacAddres = getMACAddress("wlan0"). 
	public static String getMACAddress(String interfaceName) {
		try {
			List<NetworkInterface> 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<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 device's ip address, useIPv4 can be true for ipv4 and false for ipv6
	public static String getIPAddress(boolean useIPv4) {
		try {
			List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
			for (NetworkInterface intf : interfaces) {
				List<InetAddress> 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<0 ? sAddr : sAddr.substring(0, delim);
							}
						}
					}
				}
			}
		} catch (Exception ex) { } // for now eat exceptions
		return "";
	}

    // Get the netmask
	public static String getNetmask () {
		try {
			InetAddress localHost = Inet4Address.getLocalHost();
			NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

			for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
				short prefix = address.getNetworkPrefixLength();
				if(prefix == 8){
					return "255.0.0.0";
				} if(prefix == 16){
					return "255.255.0.0";
				} if(prefix == 24){
					return "255.255.255.0";
				}
			}
			return "";
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

	}

}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.