If you use Java, Guava can help you here.
You can use InternetDomainName.topPrivateDomain()
together with publicSuffix()
to solve your problem.
Guava (as well as Mozilla/Firefox, Chrome and Opera) use the Public Suffix List for this functionality (the raw data is here).
tld.js is a JavaScript library that uses that data as well.