These days, Americans are less likely to exclaim "son of a gun" than the more-explicit "son of a b*tch," but there was a time when "son of a gun" itself was not used in mixed company — and that time was more than 200 years after the age of sail.
It seems the Royal Navy, while not keen on having women aboard its ships, sometimes overlooked the practice. Different times throughout its history saw sailors of the Royal Navy either bring either their wives or lovers aboard ships that might be out at sea for a while. While it wasn't officially tolerated, there are instances of a ship's company turning a blind eye to it.
At this point, it's important that everyone knows I'm talking about prostitutes.
Everyone aboard a ship was counted in the ship's log back in those days. The log was a detailed account of who was working, who came aboard, who left, who died, etc. It also kept track of who was born aboard one of the King or Queen's ships. It was uncommon, but it did happen. Women had to get around the world just like anyone else. The Royal Navy kept this count, just like any other ship.
But say there was one of the aforementioned female guests aboard a ship. If that woman just happened to give birth aboard ship, that child would have to be kept in the log. If a child was born with uncertain paternity — that is to say, there were too many possibilities as to who the father could be — the newborn still had to be counted in the log.
Like an old-timey recording of the Maury Show.
If this was the case, the child's name was recorded as the "son of a gun" — the son of a seaman below decks. Eventually, the common use of the phrase began to refer to any child born aboard a ship, even those of officers accompanied by their wives. Then, it began to refer to any child of a military man, not just the bastard children of sailors.
Some 200-plus years later, it's used to lovingly refer to a mischievous person or as an expression of awe or esteem. To use an expletive or insult in the same vein, we've moved on as a society. Who knows where language will go next?