Oww, Oww, Oww, just thinking about it hurts. I hate when that happens.
Take a series of quick, sharp breaths, or as some people advise – laugh.
Place your tongue on the roof of your mouth.
Count to 100 – this will help as a distraction technique and by the time you are done, it will be gone.
Brain freezes are caused by cold vessels on the roof of your mouth (like @Cruiser said). I always use the thumb on roof of mouth method. The warmth from my thumb heats up the vessels again and the brain freeze goes away. Try that next time.
Thanks for the tips, everyone. Now I feel properly armed for my next brain freeze. That has to be one of the worst feelings in the world, short lived as it may be. ;)