When you go in for an unltrasound they take a series of mesurements. These include measuring the fetus and the uterus. These measurements determine the fetal development and progression of the pregnancy.
An ultrasound can measure the month and even weeks of pregnancy by measuring the size of the fetus. The measurement is much more accurate in the early stages of pregnancy.
The ultrasound counts the months of pregnancy by checking the weight of the baby and height of the baby. These two are the main criteria and one more criteria is the organ development of the baby. By calculating all these, an ultrasound counts the months of pregnancy approximately. Accurate counts cannot be expected.
The doctor can tell how many months pregnant you are by looking at the fetus and determining how well developed it is. By that they can determine the age.
Ultrasounds allow doctors to take measurements of the fetus in certain key directions. To determine the age, one would usually measure from the top of the head to the bottom of the spine. Babies grow at fairly identical rates, especially earlier on in their development, so estimates for weeks/months of age are very consistent.