You can apply from abroad, as well as while in the United States, at the same time as you apply for your immigrant visa or change of status. If you didn’t do everything simultaneously, once in the U.S., you could apply directly at the nearest Social Security office.