They usually get worms by eating or drinking contaminated food stuffs. They can get them even after drinking contaminated milk from the mother during nursing in utero infection from the mother to the pup.
Some puppies can as well contact the worms from the mother. If the mother is infected and they are staying in the same kennel, the puppy is likely to get worms. For this reason, you need to deworm breast feeding mother every time.
Dogs also can get it by simply leaking contaminated soil, sniffing or even eating contaminated food
They can as well get it from eating infected flea
Dogs are also known to put almost everything in their mouth. They can get infected in case they get into contact with other animals feces or vomit.
If the dog feeds on an infected prey such as rodents, reptiles and birds.
If they get in contact with an infected dog. That can be when mating or playing around.