There is dispute amongst etymologists about the origin of this phrase. As always, disputes only occur where there is no definitive evidence so I’ll put the sources here and let you decide for yourself. The two points of view are primarily these:
1. The phrase originated as ‘son of a military man’ (that is, a gun).
The most commonly repeated version in this strand is that the British Navy used to allow women to live on naval ships. Any child born on board who had uncertain paternity would be listed in the ship’s log as ‘son of a gun’. This is attestable fact as, although the Royal navy had rules against it, they did turn a blind eye to women (wives or prostitutes) joining sailors on voyages, so this version has plausibility on its side.
The sources for the point of view that ‘son of a gun’ is ‘son of a military man’ are:
– Jon Badcock’s, Slang: A Dictionary of the Turf, 1823:
[son of a gun means]
‘a soldier’s bastard’.
– The Sailor’s Word-Book: an alphabetical digest of nautical terms, William Henry Smyth, 1867:
[a son of a gun is] “An epithet conveying contempt in a slight degree, and originally applied to boys born afloat, when women were permitted to accompany their husbands at sea; one admiral declared he literally was thus cradled, under the breast of a gun-carriage”.
The first known printed example of ‘son of a gun’ in print is The British Apollo No. 43, 1708:
“You’r a Son of a Gun”.
That source doesn’t mention the military and all the explanations that link ‘son of a gun’ to the military come 150 years or more later. However, Smyth was himself a Royal Navy admiral and in a better position than most to know what went on aboard naval ships. Whether or not the military/naval version is the origin it is clear that, in 1823 at least, the term was used with that meaning.
Counter to that you might think it unusual that military men didn’t appear to have daughters, or you may just put that down to the prevailing sexism of the time. There are several phrases including the word son:
Every mother’s son
Go on my son
Like father, like son
My son the doctor
Number one son
On me ‘ead, son
whereas it’s difficult to think of anything other than ‘don’t put your daughter on the stage’ for daughters.
2. The term is euphemistic and derived as a conveniently rhyming alternative to ‘son of a bitch/whore’.
‘Son of a bitch‘ has been part of the language for centuries, certainly long enough for people to some up with a euphemistic variant for it.
Shakespeare used something like it in King Lear, 1605:
“One that art nothing but the composition of a Knave, Begger, Coward, Pandar,
and the Sonne and Heire of a Mungrill Bitch.”
The military version has some circumstantial evidence to support it, the rhyming euphemism origin appears to be no more than conjecture.