You can do this by reading the file /proc/version. I contains the kernel version, distro name/version and more information. It should exist in all distributions. I actually only found this out today! :)
It seems like I was wrong, only some of the major distributions add the actual distro information to /proc/version ( i.e. Ubuntu ). So if you compile a custom kernel, I don't think it will show the name of the distro being used...
Another way, ( though again not 100% about all distributions using this ) is to look for /etc/*-release. Where * is the distro name.