ISTANBUL — Thousands of soldiers and officers purged from the military. A helicopter shot down over the capital. Hundreds of people lying dead on city streets.

As dawn broke Saturday, the citizens of Turkey emerged sleep-deprived and angst-ridden after a night of violence that felt more like life in war-stricken neighbors like Syria or Iraq.

And trying to assert control was President Recep Tayyip Erdogan, targeting plotters in the previous night’s coup and other perceived enemies of the state.

The embattled president, after a confusing absence in the early hours of the coup, appeared to speak to the nation early Saturday. He exhorted his followers with the FaceTime app from his cellphone, resorting to the kind of medium he has long sought to suppress.

That stunning scene, televised nationwide, at first seemed an embarrassment for a leader who presents himself as all-powerful and suggested his end.

But it was actually the turning point, as Mr. Erdogan called on his followers to take to the streets and gather at the airport in Istanbul, which the military had shut down, to resist the coup.

By the afternoon, after a standoff in Ankara, the capital, the government had wrested back an army headquarters building held by coup plotters. Mr. Erdogan, who had frequently talked of conspiracies afoot to undermine his power, was back in control, seemingly as powerful as ever, and perhaps even more paranoid.

The attempted coup, as it unfolded, suggested an alarming unraveling for a country that is seen in the West as a crucial partner in the fight against terrorism and an anchor of stability in a region full of trouble.

The United States has sought close cooperation with Turkey in the fight against the Islamic State, while Europe has relied on Turkey to help stem the flow of refugees from war-torn countries of the Middle East to the Continent.

“The whole night felt like doomsday,” said Sibel Samli, an independent film producer in Istanbul. “People flocked to the markets to get bread, eggs and water. People were going to cash machines to draw out cash.”

A steamy Friday was just getting going when the first hint came that something was not right: The military sealed off two bridges across the Bosporus.

Then, fighter jets and helicopters began flying low over Istanbul and Ankara, rattling residents enjoying a night on the town, and sporadic gunshots rang out.

Suddenly, Turks were transfixed by their cellphones, or the televisions in bars and restaurants, trying to figure out what was going on.

No one seemed to know where the president was.

As rumors swirled that the military was maneuvering to thwart a terror plot, or that a hijacked airliner was in the sky, many Turks, given their nation’s history of military meddling in politics, began to wonder if a coup was afoot.

Soon enough, they had their answer: The prime minister, Binali Yildirm, spoke on television and said a renegade faction within the military was trying to mount a coup.

And a military group, later calling itself the Peace at Home Council — a reference to a mantra of Turkey’s secular founder, Mustafa Kemal Ataturk — issued a statement saying it had seized control of the country.

A Surreal Evening

And so began a surreal evening that stretched until daybreak, punctuated by violence that killed at least 265 people, most of them members of the security forces, as various factions fought each other for control of the country.

The night seemed to encapsulate the many dramas and conflicts that have roiled Turkey in recent years: street protests; the bitter fight between Mr. Erdogan, an Islamist, and a onetime ally, the Muslim cleric Fethullah Gulen, whom the president late in the night blamed for the coup attempt; and rising political violence and terrorism.

Ms. Samli had been sitting with friends at a rooftop bar of a chic hotel on the European side of Istanbul when a helicopter passed low over their heads.

“We didn’t think anything of it at first because we knew the city was on high terror alerts following recent attacks,” she said. “Then we started getting the calls and WhatsApp notifications about the start of a military coup. People were calling one another telling them go home.”

The first signs that the coup might not succeed came as it become clear that the military failed to secure important government buildings, or to seize elected officials, normally the first actions of a putsch.

Video

Prime Minister Binali Yildirim of Turkey said Friday that a faction of the country's military had attempted to overthrow the government. As military forces occupied Istanbul’s Taksim Square, President Recep Tayyip Erdogan urged citizens to take to the streets.CreditCreditGurcan Ozturk/Agence France-Presse — Getty Images

Later it was learned that the conspirators had sought out Mr. Erdogan at the seaside town of Marmaris, where he was apparently vacationing, but were too late. And then Mr. Erdogan himself appeared, from an undisclosed location, and spoke to the nation on FaceTime.

Once again — as he did when he faced down a widespread street revolt in 2013 and to win elections, for himself as president and in Parliament for his Islamist Justice and Development Party — Mr. Erdogan relied on his power base of Turkey’s religious conservatives.

Mosque preachers joined Mr. Erdogan’s call to resist.

“We will not let Turkey fall!” men shouted in the conservative Istanbul neighborhood of Istinye on Saturday morning, firing guns in to the air. “God is greatest!”

The scariest hour was the one just before Mr. Erdogan’s jet landed in Istanbul after 3 a.m. Fighter jets flew low over Istanbul, setting off sonic booms that felt like airstrikes. Gunfire crackled throughout the city and in Ankara, where soldiers seized civilian cars to use as barricades. Several explosions were reported at Parliament, and a helicopter used by the plotters was blown from the sky, officials said. A helicopter landed at the offices of CNN Turk, and soldiers, apparently coup plotters, tried to seize the station during a live broadcast.

“Around 3 a.m. we heard loud fighter jets and explosions,” said Ms. Samli, the film producer in Istanbul. “That’s when I felt scared. And this morning, everyone is in shock. Everyone is trying to work out what happened.”

Late in the night, as the sounds of war mixed with muezzins at mosques exhorting people to go into the streets and people chanting “Allahu akbar,” or “God is greatest,” Turkey’s cities felt like besieged cities in Iraq or Syria.

When Mr. Erdogan landed in Istanbul, chaos was still gripping Istanbul and Ankara, with more explosions and gunshots, but his very appearance seemed to signify that the conspiracy was reaching its end.

In characteristic fashion, as he has when confronted with street protests and a corruption investigation, he vowed to root out the conspirators.

“This attempt, this move, is a great favor from God to us,” he said. “Why? Because this move will allow us to clean up the armed forces, which needs to be completely clean.”

Plotters Lacked Support

It was becoming clear, by the time Mr. Erdogan landed in Istanbul, that those behind the coup did not have enough support within the military, even as the whole episode exposed deep divisions within the military that had not been so apparent.

While the Turkish military has a history of intervening in politics — it carried out three coups in the past five decades — Mr. Erdogan and his allies had systematically sought to coup-proof the army through a series of sensational trials, and it was thought not able to mount a takeover of the government.

Officials said the main plotters were from the gendarmerie, a military-style police force; the air force; and some elements of the land forces. Several generals and colonels were arrested — none high-level figures recognizable to the public — and thousands of rank-and-file officers and soldiers were rounded up Saturday in a purge that is likely to go one for some time.

“All of these guys will go to prison for life,” said Ilnur Cevik, an aide to Mr. Erdogan, in a telephone interview Saturday afternoon.

As the night wore on, some Turks, underscoring the hold that conspiracy theories have on Turkish society, believed the whole thing was a hoax or something staged by Mr. Erdogan so he could ride to the rescue. That would give himself a pretext to crack down even further on his perceived enemies and pursue more power by establishing an executive presidency.

Video

Turks climbed aboard tanks and roughed up soldiers in Istanbul early Saturday, after the military attempted a coup Friday night.CreditCreditYasin Akgul/Agence France-Presse — Getty Images

“We didn’t know if it was real or a hoax,” Ms. Samli said. “People around us were saying that it was a staged coup orchestrated by President Erdogan to help him obtain more power over the country.”

Younger Turks panicked after seeing older Turks, who have lived through coups and the street violence that has come with them, react with horror.

“We had barely recovered from the Istanbul airport terrorist attack and now everyone has started talking about a civil war,” said Esra Goksu, 32, an artist who lives in Istanbul. “Hundreds of people died for what? One man’s ego? It breaks my heart. I don’t recognize my country anymore. I want to leave.”

An Eerie Silence

After daybreak on Saturday, when it was apparent that the coup attempt had failed, central Istanbul was eerily quiet. There was little sign of security forces, which are usually out in force at any sign of trouble, sealing streets and lining up at intersections while backed by armored vehicles.

But there were signs of life, as workers hauled trash, shops and cafes began opening, and a group of religious men on mopeds motored down Istiklal Avenue, the city’s main pedestrian street, waving the Turkish flag and chanting, “Allahu akbar!”

Across the city, the police began rounding up suspected plotters, and soldiers who had taken control of the Bosporus Bridge the night before began surrendering, leaving equipment and clothing strewn about.

“When I was waking up, I was thinking, ‘Was this a nightmare, or did we really witness these things?’” said Sinan Ulgen, a former Turkish diplomat who is the chairman of the Center for Economics and Foreign Policy Studies, a research organization in Istanbul.

Video

More than 2,800 personnel across Turkey were rounded up after the attempted coup on Friday.CreditCreditTolga Bozoglu/European Pressphoto Agency

Mr. Ulgen said of the intrigue Friday night and Saturday morning: “It was clearly a junta within the military that staged a botched coup attempt.”

But, he said, given that those arrested so far did not appear to be of the highest rank in the military, “it shows how little support the coup had within the top brass of the military.”

With Turkish society so deeply polarized, with about half the country supporting Mr. Erdogan and the other half bitterly opposed, a refusal to return to the dark days of military coups seemed to be one thing that united them as the episode unfurled over night.

While the military factions clearly did not have enough support within the military to finish the job, they also appeared to miscalculate how the plot would be received by those who have long wished to see the end of Mr. Erdogan and his government.

The coup plotters, Mr. Ulgen said, appeared to “grossly misjudge the sentiments of the Turkish people, which over time, despite Turkey’s own democratic shortcomings, have turned very anti-military intervention.”

Under Mr. Erdogan, Turkey has cracked down severely on journalists, sending many to jail and charging others with insulting Mr. Erdogan, a crime in Turkey. But ultimately, in many ways, it was modern media that helped Mr. Erdogan fend off the coup.

As the coup unfolded, he was able to communicate with the country over FaceTime, and it was anti-coup coverage of a number of Turkish outlets that, analysts said, helped sway the tide of public opinion and allow government officials a platform to communicate with the public. Among those outlets was CNN Turk, which has faced the wrath of the government over coverage officials believe to be pro-Kurdish.

The coup plotters seemed stuck in the 1970s, having seized, for a time, the state broadcaster TRT, while other news channels continued coverage, opposing the coup. Turks were able to communicate over social media, sometimes using a VPN when Twitter or Facebook seemed to be inaccessible.

“It’s a total media story,” said Asli Aydintasbas, a Turkish journalist and writer. “This was about not being able to control the message.”

Ms. Aydintasbas was attending a dinner party Friday when guests were alerted to messages on Twitter about the intrigue unfolding.

Someone joked that it might be a coup.

“We all laughed, because it’s not an option in Turkey these days,” she said. “The idea of a coup is so retro.”

Safak Timur and Karam Shoumali contributed reporting.

A version of this article appears in print on , on Page A1 of the New York edition with the headline: Turkey Cracks Down as Coup Unravels. Order Reprints | Today’s Paper | Subscribe