I had that same thing a while back. GI doc said he thought it was anal spasms. The pain was horrible and then just passed. Happened quite a few times out of nowhere while in bed and then all of a sudden it stopped and I havent had it since. Good luck.
That sounds miserable! When you have severe pain, the best thing to do is see your doctor. It could be IBS related but it almost sounds like a nerve issue. What about sciatica? I know it starts at your rectum but I wouldn't shun the idea of a nerve, sciatica or spinal issue being involved. There is something called proctalgia that you may also want to read about. This involves issues with the pelvic floor most often. Here's some info https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3218134/, let me know what you think.