That is the $64,000 question! The only explanation I can give is allegorical: each immune cell, be they dendrocytes or T-lymphocytes or whatever contains a complete library of all things "self". Whenever it comes upon a protein etc etc it checks against its list of "self" substances. If the whatever it may be is in the "self" library, then it is "self". If it is not on that list it is foreign. The actual mechanism is beyond me!