VARIOUS.TXT

Programs and patches

Various small tools

A collection of small programs, examples, and utilities.

Last updated · 3 August 2008

Here you can find some simple tools that I wrote either for fun or because I wanted to learn how use some specific techniques. Or tools that simple that they don't deserve their own category ;-)

netblock.py

Simple tool to compute an IPv4 netblock covering all IP addresses given on the command line.

For example:

~$ netblock 1.2.3.4 1.2.3.255
1.2.3.0/24

~$ netblock 192.168.131.12 192.168.137.1 192.168.144.9
192.168.128.0/19
Source: Read netblock.py below · Download raw netblock.py
dlopen() demo
A simple program demonstrating the use of per-request loadable libraries. Similar concept can be used for allowing different skins of your application.
getaddrinfo() and gethostbyname() demo
Two examples how to look up domain names and addresses.

Below are programs that I didn't write but found them useful (although I often don't know who the author is).

Compute CPU frequency
This program computes the frequency of a CPU by reading a TSC register on x86 or amd64 CPU.
DMI decode
Read, decode and print the BIOS' Desktop management interface table.

netblock.py source


#!/usr/bin/env python

## 
## netblock.py
## 
## Author: Michal Ludvig <michal@logix.cz>
##         /michal
## 
## Simple tool to compute an IPv4 netblock covering 
## all IP addresses given on the command line.
## 
## For example:
##    ~$ netblock 1.2.3.4 1.2.3.255
##    1.2.3.0/24
## 
##    ~$ netblock 192.168.131.12 192.168.137.1 192.168.144.9
##    192.168.128.0/19
## 

import sys
import socket
import struct


# functions dottedQuadToNum(), numToDottedQuad() and makeMask() taken
# from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66517
# and made endian-agnostic
def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"
    return struct.unpack('>L',socket.inet_aton(ip))[0]

def numToDottedQuad(n):
    "convert long int to dotted quad string"
    return socket.inet_ntoa(struct.pack('>L',n))

def makeMask(n):
    "return a mask of n bits as a long integer"
    return ~((2L<<n-1)-1)

def commonSubnet(ips):
        "compute a netblock covering all IPs in list 'ips'"
        ipn = [dottedQuadToNum(ips.pop(0)), dottedQuadToNum(ips.pop(0))]

        ipnum = ipn[0] ^ ipn[1]

        for i in range(31, 0, -1):
                if ipnum & (1L<<i) != 0:
                        i += 1
                        break
        mask = makeMask(i)
        net = numToDottedQuad(ipn[0] & mask)
        if ips:
                return commonSubnet([net] + ips)
        return net, 32-i

if __name__ == "__main__":
        try:
                print "%s/%d" % commonSubnet(sys.argv[1:])
        except:
                print "Usage: %s <ip1> <ip2> ... <ipN>"
                sys.exit(1)

Download raw netblock.py ↓

getaddrinfo.c source


/* 
 * getaddrinfo.c - Simple example of using getaddrinfo(3) function.
 * 
 * Michal Ludvig <michal@logix.cz> (c) 2002, 2003
 * /devel/
 *
 * License: public domain.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int
lookup_host (const char *host)
{
  struct addrinfo hints, *res;
  int errcode;
  char addrstr[100];
  void *ptr;

  memset (&hints, 0, sizeof (hints));
  hints.ai_family = PF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags |= AI_CANONNAME;

  errcode = getaddrinfo (host, NULL, &hints, &res);
  if (errcode != 0)
    {
      perror ("getaddrinfo");
      return -1;
    }

  printf ("Host: %s\n", host);
  while (res)
    {
      inet_ntop (res->ai_family, res->ai_addr->sa_data, addrstr, 100);

      switch (res->ai_family)
        {
        case AF_INET:
          ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
          break;
        case AF_INET6:
          ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr;
          break;
        }
      inet_ntop (res->ai_family, ptr, addrstr, 100);
      printf ("IPv%d address: %s (%s)\n", res->ai_family == PF_INET6 ? 6 : 4,
              addrstr, res->ai_canonname);
      res = res->ai_next;
    }

  return 0;
}

int
main (int argc, char *argv[])
{
  if (argc < 2)
    exit (1);
  return lookup_host (argv[1]);
}

Download raw getaddrinfo.c ↓

gethostbyname.c source


/*
 * gethostbyname.c - Example of using gethostbyname(3)
 * Martin Vidner <mvidner@suse.cz>
 */

#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>

struct hostent *he;
struct in_addr a;

int
main (int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "usage: %s hostname\n", argv[0]);
        return 1;
    }
    he = gethostbyname (argv[1]);
    if (he)
    {
        printf("name: %s\n", he->h_name);
        while (*he->h_aliases)
            printf("alias: %s\n", *he->h_aliases++);
        while (*he->h_addr_list)
        {
            bcopy(*he->h_addr_list++, (char *) &a, sizeof(a));
            printf("address: %s\n", inet_ntoa(a));
        }
    }
    else
        herror(argv[0]);
    return 0;
}

Download raw gethostbyname.c ↓

compute_MHZ.c source


#include <stdio.h>
#include <sys/time.h>

__inline__ unsigned long long int rdtsc()
{
        unsigned long long int x;
        __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
        return x;
}

int
main ()
{
        struct timezone tz;
        struct timeval tvstart, tvstop;
        unsigned long long int cycles[2]; /* gotta be 64 bit */
        unsigned int microseconds; /* total time taken */

        bzero(&tz, sizeof(tz));

        /* Load this function a cached memory. */
        gettimeofday(&tvstart, &tz);

        /* Read TSC for the first time and get timestamp.  */
        cycles[0] = rdtsc();
        gettimeofday(&tvstart, &tz);

        /* We don't trust that this is any specific length of time.
           We don't even care how long time we'll sleep. */
        sleep(1);

        /* Read TSC for the second time and get timestamp.  */
        cycles[1] = rdtsc();
        gettimeofday(&tvstop, &tz);

        /* Compute the frequency.  */
        microseconds = ((tvstop.tv_sec-tvstart.tv_sec)*1000000) +
                (tvstop.tv_usec-tvstart.tv_usec);
        printf("%f MHz processor.\n",
                (float)(cycles[1]-cycles[0])/microseconds);

        return 0;
}

Download raw compute_MHZ.c ↓

EXPLORE

Various small toolsUTF-8 · LOGIX.CZ

Find in Logix

Search page titles and descriptions. Esc closes.

A few handy keys

A little Borland, a little early desktop, a corner of the web to call home.

Pick a directory from the menu or tree. Use Find when you know what you’re after.

Tab / Shift+Tab
Move between controls
↑ / ↓ in menus
Choose an entry
← / → in menus
Switch directories
/
Find a page
Esc
Close menu or dialog
F1
Open this help

Prefer a different atmosphere? View has blue, grey, and green palettes.

No commands to learn. Just follow your curiosity.