You should use the GL_SELECT render mode for this-- a nice tutorial can be found here :)