nc – “Netcat”

My favorite tool of the day is nc, or Netcat.

Like most unix programs, it’s a well-documented single purpose application. From the man page:

The nc (or netcat) utility is used for just about anything under the sun involving TCP or UDP.  It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6.  Unlike telnet(1), nc scripts nicely, and separates error messages onto standard error instead of sending them to standard output, as telnet(1) does with some.

This is particularly handy when debugging network applications. Instead of wondering whether bugs lie in your application code or in the server, you can simply point your application to nc to easily see what’s being sent across the wire.

To illustrate the simplicity, let’s send “Hello world” between terminal windows (this could be across the world almost as easily).

Start by opening a terminal window and typing “nc -l 4567”. This command tells netcat to listen for incoming TCP connections on port 4567.

Screen Shot 2013-11-13 at 10.37.33 PMNext, open a second terminal window and type “nc localhost 4567”. This command tells netcat to connect to localhost (the current machine) on port 4567. This connection will succeed because we’re the ones listening.Screen Shot 2013-11-13 at 10.39.30 PM

You’ll notice it looks like the program is hanging, but start typing into the terminal and press enter/return and you’ll see each line appear in the first terminal like magic.

Screen Shot 2013-11-13 at 10.42.10 PMScreen Shot 2013-11-13 at 10.42.13 PMKilling the second window will close the connection.

Additional applications for this include sending files over the connection (via netcat localhost 4567 < file.format).

Android 4.4 – KitKat – Step detector code

One of the new features in Android 4.4, KitKat is the “Step Counter” and “Step Detector” sensors.

I wrote a quick sample app that utilizes the step counter. It acts like a simple pedometer, registering for the sensor events when it starts, and updating the UI with the latest step count whenever a new event is returned.

This updating won’t be in real-time, as the system batches up events. The code currently specifies SensorManager.SENSOR_DELAY_NORMAL as the update frequency – this amounts to 200000 microseconds, or 5 updates a second (should be good enough, even if you duct tape your phone to a cheetah).

I’m using the TYPE_STEP_COUNTER Sensor, which dispatches an event with the total number of steps periodically when a new step is detected. The other Sensor is TYPE_STEP_DETECTOR, which fires a timestamp sensitive event with every detected step (rather than the total number of steps detected so far).

For now, this only works on a Nexus 5 running KitKat, since the API was added in KitKat and the Nexus 5 is the first device to ship with a dedicated low-power step detecting chip.

The code is available on GitHub: android-step-counter