Thursday, 29 November 2012

Getting your own (IP) address and port in a javascript web app

While hacking something up using socket.io I needed to know the IP of the server, so I could connect a socket back to it. localhost was the solution at first, but I wanted to access it from other machines in my network.

I didn't want to get the local IP using node. I might want to serve the application from a server with more than one network card. I needed to have the IP fixed.

But I often develop the app while commuting, on my EEEPC. When I get home, I sync my code as I turn on my desktop computer to proceed work.

So I found myself needing to have a fixed IP over two different machines: my desktop PC, and my EEEPC. A fixed IP was clearly not an option.

I had the idea of using window.location. I used window.location.hostname to get the IP address or domain name of any server I was connected to. It was such a simple solution I was very positively surprised.

All uses of window.location:

example url: http://192.168.1.7:8080/chat?nickname=F%C3%A1bio#fragment

  • hash (#fragment)
  • host (192.168.1.7:8080)
  • hostname (192.168.1.7)
  • href (http://192.168.1.7:8080/chat?nickname=F%C3%A1bio#fragment)
  • pathname (/chat)
  • protocol (http:)
  • search (?nickname=F%C3%A1bio)

No comments:

Post a Comment