Browsing HN or Facebook or reading Twitter is the bad kind of distraction. I block news.ycombinator.com and some other websites on my computer (by editing the hosts file) to avoid the "let me just quickly check something" trap.
But I find that I get distracted most easily when doing boring pointless work. So I try my best to avoid that kind of work and make sure most of my work is intersting. When the work is interesting, I tend not to get distracted so easily.
One thing I find useful to stay focussed, is when a distracting idea comes to mind is to simply write it down somewhere, so I can look into it later.
If other people are a distraction, you need to make some time where you cant be interrupted. Switch your phone to airplane mode.
Tell people you are working and not to disturb you at certain times, or just let them know you will get back to them later. If you aren't a jerk about communicating this, most people are pretty reasonable.