  (Abridged) Based on XMM-Newton, Chandra and SDSS data, we investigate the
baryon distribution in groups and clusters and its use as a cosmological
constraint. For this, we considered a sample of 123 systems, with total masses
in the mass range M500 = ~ 10^13 - 4 x 10^15 h_70^-1 Msun.
  The gas masses and total masses are derived from X-ray data under the
assumption of hydrostatic equilibrium and spherical symmetry. The stellar
masses are based on SDSS-DR8 data. For the 37 systems out of 123 that had both
optical and X-ray data available, we investigated the gas, stellar and total
baryon mass fractions inside r2500 and r500, and the differential gas mass
fraction within the spherical annulus between r2500 and r500, as a function of
total mass. For the other objects, we investigated the gas mass fraction only.
We find that the gas mass fraction inside r2500 and r500 depends on the total
mass.
  However, the differential gas mass fraction does not show any dependence on
total mass for systems with M500 > 10^14 Msun. We find that the total baryonic
content increases with cluster mass. This led us to investigate the
contribution of the ICL to the total baryon budget for lower mass systems, but
we find that it cannot account for the difference observed. The gas mass
fraction dependence on total mass observed for groups and clusters could be due
to the difficulty of low-mass systems to retain gas inside the inner region.
Due to their shallower potential well, non-thermal processes are more effective
in expelling the gas from their central regions outwards. Since the
differential gas mass fraction is nearly constant it provides better
constraints for cosmology.
  Using our total f_b estimates, our results imply 0.17 < Omega_m < 0.55.
