At least five people were killed in the attack at the Afrik Hotel, which began with a car bomb on Sunday.
Al-Shabab said it was responsible. The group, which is linked to al-Qaeda, regularly carries out attacks against the government.
At least four attackers also died – according to AFP news agency three were shot and one blew himself up.
A car hit the hotel’s front entrance and detonated before gunmen stormed the building, according to officials and others at the scene.
“The blast made the hotel tremble as we sat inside and were talking. We were panicked, confused,” eyewitness Ahmed Nur was quoted by Reuters as saying.
“The operation is over now. Nine people, including four attackers, died and over 10 civilians were injured. There is no electricity,” a police spokesman told reporters from the scene and via Facebook.
Prime Minister Mohamed Hussein Roble said in a statement that among those killed was a former military general, Mohamed Nur Galal.
The militants targeted the Afrik Hotel despite the fact that it is in a heavily guarded area near the city’s main airport, the BBC’s Bella Sheegow reported from Mogadishu.
The hotel is known to be a gathering place for Somali government officials. A local police captain said a number of lawmakers and senior military officials were inside at the time of the attack.
Footage on social media showed large plumes of smoke rising across the city earlier on Sunday.
Our reporter says it was one of the most devastating recent attacks in Mogadishu. Al-Shabab also targeted the beachside Elite hotel last year resulting in a seven-hour battle with police and security in which 17 people were killed.
The violent siege comes just weeks after former US President Donald Trump ordered the withdrawal of some 700 troops who had been supporting local security forces against militant groups, including al-Shabab.
There are fears the withdrawal could lead to further instability in the country, which is due to hold elections next month.