To retrieve a URL object containing the full beginning portion of the URL, such as "https://na17.salesforce.com", you may use the static method:
System.URL.getSalesforceBaseURL(); // Yields URL object for https://xxxx.salesforce.com
As Ashish notes above, suffixing this method with ".toExternalForm()" will convert the URL object into its text representation, as follows:
System.URL.getSalesforceBaseURL().toExternalForm(); // Yields string "https://xxxx.salesforce.com"
Furthermore, if you wish to retrieve only the subdomain portion of the URL (the "na17" part to the left of the ".salesforce.com" domain), use:
System.URL.getSalesforceBaseURL().getHost(); // Yields subdomain (host) as string
These methods will work reliably across Production, Sandboxes, Dev Orgs, etc. Which one you choose depends upon your specific need in the code that you are writing.
Lastly, if you're trying to create a host-independent object link, you may do so as follows:
String link = '<a href="' + System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + sObject.Id + '" target="_blank">sObject Link</a>';