At least 42 people have been killed in clashes between Islamic State, a rival Islamist group and forces loyal to the official government in two Libyan cities, residents and medics said on Friday.

The fighting typifies the chaos in the oil-producing country, where two governments, former rebels and Islamist groups are battling for control, four years after the ousting of veteran ruler Moammar Gadhafi.

In the main eastern city, Benghazi, Islamic State attacked forces loyal to the official government. They killed five soldiers and destroyed a tank and three military vehicles, residents and medics said.