Thousands of military homes will be brought back into public ownership at a cost of almost £6 billion.