However, as I have already said, I really don't recommend using such detection in any real project as it does not do what you may think it does. It essentially figures out what IP system hostname resolves to from the server itself. It is extremely reliant on server and network configuration and only happens to work if this hostname is exported to global DNS servers and your HTTP server is bound exactly to it and no local DNS server interferes. And probably lot of other possible issues that did not came to my mind at once.

What to you want to use it for? Maybe I can recommend a more robust alternative?