validate ip address using regex

The code snippet below will check if the passed string is a valid IP address or not .
An Internet Protocol address (IP address) is a numerical label assigned to each device participating in a computer network that uses the Internet Protocol for communication. Read more about IP address here. This snippet will validate IP version 4 addresses.

/**
 * validate IP address
 * @param String IP address to verify
 * @return Boolean result
 */
public static Boolean isIP(String input) {
    if (input!= null && !input.isEmpty()) {
        //Regex
        String regex = "^((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\d)(\\.((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\d)){3}$";
        //check if input matches the regex
        if (text.matches(regex)) {
            // valid ip
            return true;
        } else {
            // invalid ip
            return false;
        }
    }
    // invalid input
    return false;
}  

 

isOnline() check if android device has internet connectivity

What do you want?

  • If you just want to check for a connection to any network – not caring if internet is available – then most of the answers here (including the accepted), implementing isConnectedOrConnecting() will work well.
  • If you want to know if you have an internet connection (as the question title indicates) please read on

Ping for the main name servers

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
       Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e)          { e.printStackTrace(); } 
      catch (InterruptedException e) { e.printStackTrace(); }
    return false;
}

That’s it! Yes that short, yes it is fast, no it does not need to run in background, no you don’t need root privileges.

Possible Questions

  • Is this really fast enough?Yes, very fast!
  • Is there really no reliable way to check if internet is available, other than testing something on the internet?Not as far as I know, but let me know, and I will edit my answer.
  • Couldn’t I just ping my own page, which I want to request anyways?Sure! You could even check both, if you want to differentiate between “internet connection available” and your own servers beeing reachable
  • What if the DNS is down?Google DNS (e.g. 8.8.8.8) is the largest public DNS service in the world. As of 2013 it serves 130 billion requests a day. Let ‘s just say, your app not responding would probably not be the talk of the day.
  • Which permissions are required?
    <uses-permission android:name="android.permission.INTERNET" />

    Just internet access – what surprise ^^ (BTW have you ever thought about, how some of the methods suggested here could even have a remote glue about the availability of internet, without this permission?)

 

Android: How to get MAC address of Ethernet port (not WiFi)

There are some android devices that have an ethernet (LAN) port for example Android STB, Android powered door-phone monitors, etc. The regular way of getting MAC address is as follows

WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();

Not to forget adding the following permission in the AndroidManifest.xml 

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

The above method will give us the MAC address of WiFi. Assuming your Ethernet interface is eth0, to get the MAC address of Ethernet port we have to try opening and reading the file /sys/class/net/eth0/address. This can be Implemented as below.

public static String loadFileAsString(String filePath) throws java.io.IOException{
    StringBuffer data = new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    char[] buf = new char[1024];
    int numRead=0;
    while((numRead=reader.read(buf)) != -1){
        String readData = String.valueOf(buf, 0, numRead);
        data.append(readData);
    }
    reader.close();
    return data.toString();
}

public String getMacAddress(){
    try {
        return loadFileAsString("/sys/class/net/eth0/address")
                .toUpperCase().substring(0, 17);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 

easyavr.h Header file for pin/port operations

Here I am sharing a header file called easyavr.h. This is a pretty basic header file with some helper functions related to input output pins of AVR

#ifndef __EASYAVR_H_
#define __EASYAVR_H_


//  Sets pin of port to 1
//
//  Example for PD2: PIN_ON(PORTD, 2)
#define PIN_ON(port,pin) ((port) |= (1 << (pin)))


//  Sets pin of port to 0
//
//  Example for PD2: PIN_OFF(PORTD, 2)
#define PIN_OFF(port,pin) ((port) &= ~(1 << (pin)))


//  Sets pin of port to value
//
//  Example for PD2: PIN_SET(PORTD, 2, 1)
#define PIN_SET(port,pin,val) (((val) > 0) ? PIN_ON((port),(pin)) : PIN_OFF((port),(pin)))

//  Sets all of port pins to OUTPUT mode
//
//  Example for PORTD: PORT_AS_OUTPUT(PORTD)
#define PORT_AS_OUTPUT(port) ((port) = 0xFF)

//  Sets all of port pins to INPUT mode
//
//  Example for PORTD: PORT_AS_INPUT(PORTD)
#define PORT_AS_INPUT(port) ((port) = 0x00)

//  Sets pin of port to OUTPUT mode
//
//  Example for PD1: PORT_AS_OUTPUT(DDRD, 1)
#define PIN_AS_OUTPUT(ddr,pin) ((ddr) |= (1 << (pin)))


//  Sets pin of port to INPUT mode
//
//  Example for PD1: PORT_AS_INPUT(DDRD, 1)
#define PIN_AS_INPUT(ddr,pin) ((ddr) &= ~(1 << (pin)))

//  Checks pin's value of port
//  Returns 1 or 0
//
//  Example for PD2: CHECK_PIN(PIND, 2)
#define CHECK_PIN(pinreg,pin) (((pinreg) & (1 << (pin))) != 0)


#endif
 

validating a base64 encoded string using regular expression

We can validate a base64 encoded string using a nice regex (regular expression). The following regex can be used with any programming language. I would use php for the example. The regex is as follows.

^[a-zA-Z0-9/+]*={0,2}$

Which will also detect the usage of = or == at the end of the string (and only end).

A function geared specifically toward this:

<?phpfunction is_base64_encoded()
 {
     if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
           return TRUE;
      } 
     else {
             return FALSE;
       }
 };
 is_base64_encoded("iash21iawhdj98UH3"); // true
 is_base64_encoded("#iu3498r"); // false
 is_base64_encoded("asiudfh9w=8uihf"); // false
 is_base64_encoded("a398UIhnj43f/1!+sadfh3w84hduihhjw=="); // false
?>
 

Android snippet: validate a hex number input

This is how you can validate a hex input in android code. The regex it makes use of can be used in other languages as well.

Validation steps are :

  • check if the input is not null or zero length
  • check if the input has even numbers as hex numbers are always even
  • match the input with the validating regex.
public boolean validHexInput(String str) {

   if (str == null || str.length() == 0) {
      return false;
   }

   // length should be even number 
   // otherwise its not a valid hex 
   if (str.length() % 2 == 0) {
      String var1 = "(?i)[0-9a-f]+";
      return str.matches(var1);
 }

 return false;
}

 

Android: Call to getLayoutInflater() outside activity

Some times we need the inflater outside activities in android . To get access to the inflator we may use the following code snippet. You can use this outside activities – all you need is to provide a Context:

LayoutInflater inflater = LayoutInflater.from(context);

the from function also checks with assert that you actually get an inflater back and throws an error otherwise – which will be much easier to deal with then a null pointer exception somewhere in the code.

An Alternate way is shown below but I recommend to use the above one:

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

Then to retrieve your different widgets, you inflate a layout:

View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );
 

Android: Updating the text of Toast message instantly

In my app,I wanted to show the number of taps to be made to accomplish a task, for this purpose i used Toast class , I used Toast.makeText to show the text. problem is that I couldn’t change the text or make it hide quickly if new text was to be shown. Android would queue all the makeText requests.

I wanted to have a solution to be able to change the text or be able to cancel the previous toast without waiting for it to finish. While Looking for solution I found this class called Boast by a StackOverFlow user Richard Le Mesurier. The Boast class accomplishes exactly what I needed.

The trick is to keep track of the last Toast that was shown, and to cancel that one.

What Richard Le Mesurier have done is to create a Toast wrapper, that contains a static reference to the last Toast displayed.

When I need to show a new one, I first cancel the static reference, before showing the new one (and saving it in the static).

Here’s full code of the Boast wrapper Richard Le Mesurier made – it mimics enough of the Toast methods for me to use it.

By default the Boast will cancel the previous one, so you don’t build up a queue of Toasts waiting to be displayed.

This should be a direct drop-in replacement for Toast in most use cases. for example

 mBoast.makeText(this,"your text",Duration).show();
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.widget.Toast;

/**
 * {@link Toast} decorator allowing for easy cancellation of notifications. Use
 * this class if you want subsequent Toast notifications to overwrite current
 * ones. </p>
 *
 * By default, a current {@link Boast} notification will be cancelled by a
 * subsequent notification. This default behaviour can be changed by calling
 * certain methods like {@link #show(boolean)}.
 */
public class Boast
{
    /**
     * Keeps track of certain {@link Boast} notifications that may need to be cancelled.
     * This functionality is only offered by some of the methods in this class.
     */
    private volatile static Boast globalBoast = null;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Internal reference to the {@link Toast} object that will be displayed.
     */
    private Toast internalToast;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Private constructor creates a new {@link Boast} from a given
     * {@link Toast}.
     *
     * @throws NullPointerException
     *         if the parameter is <code>null</code>.
     */
    private Boast(Toast toast)
    {
        // null check
        if (toast == null)
        {
            throw new NullPointerException(
                    "Boast.Boast(Toast) requires a non-null parameter.");
        }

        internalToast = toast;
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Make a standard {@link Boast} that just contains a text view.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text,
                                 int duration)
    {
        return new Boast(Toast.makeText(context, text, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the
     * text from a resource.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId, int duration)
            throws Resources.NotFoundException
    {
        return new Boast(Toast.makeText(context, resId, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view. Duration
     * defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text)
    {
        return new Boast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the
     * text from a resource. Duration defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId)
            throws Resources.NotFoundException
    {
        return new Boast(Toast.makeText(context, resId, Toast.LENGTH_SHORT));
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Show a standard {@link Boast} that just contains a text view.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     */
    public static void showText(Context context, CharSequence text, int duration)
    {
        Boast.makeText(context, text, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the
     * text from a resource.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    public static void showText(Context context, int resId, int duration)
            throws Resources.NotFoundException
    {
        Boast.makeText(context, resId, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view. Duration
     * defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     */
    public static void showText(Context context, CharSequence text)
    {
        Boast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the
     * text from a resource. Duration defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    public static void showText(Context context, int resId)
            throws Resources.NotFoundException
    {
        Boast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Close the view if it's showing, or don't show it if it isn't showing yet.
     * You do not normally have to call this. Normally view will disappear on
     * its own after the appropriate duration.
     */
    public void cancel()
    {
        internalToast.cancel();
    }

    /**
     * Show the view for the specified duration. By default, this method cancels
     * any current notification to immediately display the new one. For
     * conventional {@link Toast#show()} queueing behaviour, use method
     * {@link #show(boolean)}.
     *
     * @see #show(boolean)
     */
    public void show()
    {
        show(true);
    }

    /**
     * Show the view for the specified duration. This method can be used to
     * cancel the current notification, or to queue up notifications.
     *
     * @param cancelCurrent
     *        <code>true</code> to cancel any current notification and replace
     *        it with this new one
     *
     * @see #show()
     */
    public void show(boolean cancelCurrent)
    {
        // cancel current
        if (cancelCurrent && (globalBoast != null))
        {
            globalBoast.cancel();
        }

        // save an instance of this current notification
        globalBoast = this;

        internalToast.show();
    }

}
 

How to Turn a Raspberry Pi into NVR or DVR With Motion

Raspberry Pi is a low-cost micro-computer that is able to run Linux and has endless extension possibilities then can be also used for network video recorder (NVR) is a software program that records video in a digital format to a disk driveUSB flash drive, SD memory card or other mass storage device.

This post will guide you through the process of setting up your Raspberry Pi as a Network video recorder (NVR)

Requirements

You are going to need the following:

  • A Raspberry Pi
  • An Internet connection
  • An SD Card flashed with Raspbian OS (> 8 Gb)
  • IP or Analog camera with mjpeg streaming support or USB Camera (If you want record from Raspberry’s camera module, Please visit “Raspberry Pi as low-cost HD surveillance camera“)

Continue Reading …