Lets say there are two public IP addresses. One is 18.104.22.168/16 and the other is 22.214.171.124/8, they are different network IDs but when used over the internet how are they both differentiated? Or is it that classful addressing is used for public IPs and classless is used for private?
They're not differentiated. The subnet size - or prefix length - is only relevant for routing table entries (which each carry a length field) or for a locally connected subnet where the host is configured with a specific netmask (statically or by DHCP).
One is 126.96.36.199/16 and the other is 188.8.131.52/8, they are different network IDs
While both describe differently sized networks, the address is the same. The /16 network is just a subnet of the /8 network.
A subnet mask isn't ever detected. For a pure address the mask is simply irrelevant. An end-node host only needs to know its own subnet prefix length which is either statically configured or by DHCP. Route entries on a router (or on a host for that matter) are also either statically configured by the admin or learned via a routing protocol like OSPF or RIPv2, where the mask lengths are passed along as well.
Classful networking was obsoleted in 1993 by RFC 1518. Note that even when classful networking was used, different netmask sizes were possible - they just defaulted to their class length (and were handed out by the RIRs that way).