Deriving unique server IDs from IP addresses

When building distributed systems, each server must have a unique identifier. In environments like MySQL replication clusters, that ID must be a number. A practical and reliable approach is to derive it from the server’s IP address.

This works because IP addresses are guaranteed to be unique within a subnet. No two servers can share the same IP on the same network, so converting an IP address to its decimal equivalent guarantees a unique numeric ID. It also works reliably in environments where servers are ephemeral – as long as no two servers share an IP at the same time, the derived IDs will never collide.

Converting an IP address to a decimal number

Save the following as ip2dec and make it executable:

#!/usr/bin/awk -f
BEGIN {
  ip = ARGV[1]
  split(ip, octets, ".")
  for (i = 1; i <= 4; i++) {
    dec += octets[i] * 256 ** (4 - i)
  }
  printf("%i\n", dec)
}
$ chmod +x ip2dec
$ ./ip2dec 192.168.1.1
3232235777

The script accepts any IP address from 0.0.0.0 to 255.255.255.255 and outputs its decimal equivalent in the range 0 to 4294967295.

Converting a decimal number back to an IP address

Save the following as dec2ip and make it executable:

#!/usr/bin/awk -f
BEGIN {
  dec = ARGV[1]
  for (e = 3; e >= 0; e--) {
    octet = int(dec / (256 ^ e))
    dec -= octet * 256 ^ e
    ip = ip delim octet
    delim = "."
  }
  printf("%s\n", ip)
}
$ chmod +x dec2ip
$ ./dec2ip 3232235777
192.168.1.1

Anything outside the range 0 to 4294967295 will produce unexpected results.

Practical use: MySQL server IDs

In a MySQL replication cluster, every node requires a unique server_id. Rather than tracking and assigning IDs manually, derive them from each node’s IP address:

$ ./ip2dec 192.168.1.10
3232235786
$ ./ip2dec 192.168.1.20
3232235796
$ ./ip2dec 192.168.1.30
3232235806

Each result maps directly to a unique server_id. The conversion is deterministic and repeatable, and leverages the uniqueness guarantee already built into your network. The dec2ip script lets you reverse the lookup if you need to trace an ID back to its host.

Installation

Place both scripts somewhere on your PATH:

$ mkdir -p ~/bin
$ cp ip2dec dec2ip ~/bin/
$ export PATH="$HOME/bin:$PATH"

Both scripts are then available system-wide without a path prefix.

Leave a Reply