The easiest way to retrieve a site's icon programmatically is to use the http://grabicon.com service, and I'm not just saying that because I created it :)
It's a drop-in replacement for google's S2 service - it's free, lets you specify the icon size you want, and generates unique default icons for sites that don't have one. Just do this:
Or if you want a size other than the default 32px:
If you use jQuery, grabicon also has a code snippet that will "iconify" all the external links on your page. Best of all, it's actually supported - google's service is not intended for public use, so it could go away at any time.
If you have any questions or requests for features, please don't hesitate to ask.