Recently i wanted to get the MAC addresses of the computer i was working from within my Java program. I started a small quest and all over there was this tip “this is system dependent so you need to make system calls”. Somewhere around there i found a “but”. Someone posted that in mustang (that is jdk 1.6 or jre 6) tings have changed a little and you can get all this info from a Java class without a system call.

Don’t get me wrong, system calls are not bad but there is a major defect on that approach. When you do a system call there goes the “write once, run everywhere”. I mean you get system dependent. If there is an absolute need to do so and there is no other solution i guess that is ok. But when i stumble upun such problems i always try to find out a way to do it without getting system dependent.

Enough with the fluff. Let’s get down to the point. The main classes you need to concentrate on are java.net.InetAddress and java.net.NetworkInterface. With these two you can do all the dirty job. Now, if you feel adventurus then stop reading and go find your way around after this tip. If you want the solution keep going 😉

try {
	InetAddress []mac = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
	/*
	 * Get NetworkInterfaces for the current host and then read the
	 * hardware addresses.
	 */
	for(int i=0; i
< mac.length; i++) {
			System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
		}
		System.out.println();
	}
}

Easy huh? This way all you do is list all the network devices on the machine and get the MAC addresses. Make one thing clear though. It’s all the devices. In my machine that meant both real and virtual devices (such as some microsoft bridges and the VMware ones). So if you want to do something with one of them beware which one you choose 😉