A video posted by the Anadolu news agency shows a smiling Ahmadinejad shaking hands with a crowd of supporters at Cairo's al-Husseina mosque on Tuesday when at least one man threw a shoe toward him. Other men also threw shoes at Ahmadinejad, the Egyptian public prosecutor's office said.
"You killed our brothers!" one of the assailants shouted, according to Anadolu. The agency said the man's shoe struck a security guard.
The men behind the attack were four Salafis, the prosecutor's office said.
The four men were released on bail for 500 Egyptian pounds each, CNN reported, quoting the prosecutors' office as saying.
Salafis follow the Sunni Muslim doctrine and oppose the idea of Shiite Muslims engaging in any political activity in Egypt. They have accused Iran of financing Shiites to spread the Shia doctrine in Egypt, which has a Sunni majority.
Ahmadinejad is the first Iran leader to visit Egypt since the 1979 Islamic revolution.
There was embarrassment earlier on Wednesday when Egypt's top Sunni cleric, Sheikh Ahmed al-Tayeb, warned Ahmadinejad over Iran's approach to Sunni Arab nations.
Tayyeb, the grand sheikh of al-Azhar, Sunni Islam's leading authority, Iran should not interfere in the internal affairs of Gulf states and seek the "extension of Shia reach", the BBC reported.