coderrr

May 28, 2008

Get your local IP address

Filed under: network, ruby — Tags: , — coderrr @ 10:18 pm

Shameless Plug: Hide your IP address from snooping websites to regain your privacy with a VPN Service.

This came up from someone’s question on IRC. Here’s a simple way to get your local IP address in Ruby without spawning a shell and without making a connection.

require 'socket'

def local_ip
  orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off reverse DNS resolution temporarily

  UDPSocket.open do |s|
    s.connect '64.233.187.99', 1
    s.addr.last
  end
ensure
  Socket.do_not_reverse_lookup = orig
end

# irb:0> local_ip
# => "192.168.0.127"

The above code does NOT make a connection or send any packets (to 64.233.187.99 which is google). Since UDP is a stateless protocol connect() merely makes a system call which figures out how to route the packets based on the address and what interface (and therefore IP address) it should bind to. addr() returns an array containing the family (AF_INET), local port, and local address (which is what we want) of the socket.

This is a good alternative to `ifconfig`/`ipconfig` solutions because it doesn’t spawn a shell and it works the same on all systems.

Anyone know a better way?

19 Comments »

  1. This didn’t work for me. What do I need to require:

    uninitialized constant Socket

    Comment by Mike McKay — July 3, 2008 @ 10:39 am

  2. require ‘socket’

    Comment by coderrr — July 3, 2008 @ 2:57 pm

  3. request ‘socket’

    (replying to myself) :-)

    Comment by Mike McKay — July 3, 2008 @ 4:00 pm

  4. What about this ;)

    require ‘socket’
    Socket::getaddrinfo(Socket.gethostname,”echo”,Socket::AF_INET)[0][3]

    Comment by Alex MacCaw — July 22, 2008 @ 9:14 am

  5. @Alex

    Thanks for the comment.

    I can do a one liner too :P

    UDPSocket.open {|s| s.connect(’64.233.187.99′, 1); s.addr.last }

    Being serious though, I think there are a few issues with yours…

    1) I’m not sure you can assume that every computer will have a hostname that is setup to resolve to its local ip.
    2) On my computer getaddrinfo returns 3 address arrays back because I have multiple interfaces (some stuff VMware created). The correct one happens to be first but I doubt that will be the case for all computers.

    We want to get the IP for the interface which external traffic goes out through. I’m pretty sure my code guarantees that’s what we get. I don’t think yours does.

    Thanks for posting the solution though. I hadn’t thought of doing it that way.

    Comment by coderrr — July 23, 2008 @ 1:10 am

  6. Hey, that’s a clever method. I do ifconfig parsing for my own scripts, but I was never thrilled about it. Is there also a simple way of showing the main interface (the interface that it would have used to send the packet)? I parse netstat for that, but again, not optimal.

    Btw, I know this is half a year late, but programming blogs are wikis too, right?

    Comment by guns — February 24, 2009 @ 6:10 am

  7. hey guns

    I’m not sure if there is a way to get the “main” interface. Because it’s possible to have your routing set up so that packets going to one network go out one interface and packets going somewhere else go out another.

    Comment by coderrr — February 24, 2009 @ 9:23 am

  8. Oh yeah, I suppose I forgot to consider that.

    I suppose the question then is how to get the interface that is used to send the packet towards the ip of your choice. This would be really quite useful actually.

    Comment by guns — March 2, 2009 @ 2:43 am

  9. Ah I see, I misunderstood what you were asking.

    As far as I know Ruby has no APIs for getting information about the actual network interfaces.

    Comment by coderrr — March 3, 2009 @ 10:20 am

  10. brilliant solution! very helpful! :)

    Comment by ba — April 17, 2009 @ 7:59 pm

  11. this works great on command prompt.
    how do we have to use this code to display on web browser.

    Actually I want to display visitors IP address on my rail application webpage. so where do I have to put this code.

    Comment by alpa — June 4, 2010 @ 7:14 pm

  12. Nice Brother

    http://www.tipskhazana.blogspot.com

    Comment by tips khazana — June 25, 2010 @ 5:45 am

  13. I have tried to write a response here and every time I submit it refreshes the screen or provides an error. Can the author possibly look into the reason this is happening?

    Comment by Shawn Demoranville — June 25, 2010 @ 8:40 am

  14. [...] הנה דרך שהיא בנתיים הכי טובה שאני נתקלתי לבצע את המשימה…: [...]

    Pingback by מה כתובת ה IP איתה אני יוצא מהמחשב שלי החוצה ? « לראות שונה — July 12, 2010 @ 6:47 am

  15. Could you please tell me what is this 64.233.187.99 . Can it be the Ip of any machine that is reachable from our machine . Or is it something specific ?

    Comment by Kunar — January 11, 2011 @ 9:44 am

  16. Oh, man.

    Comment by Sprmcandy — March 11, 2011 @ 7:43 pm

  17. Thanks.

    Comment by BeingHuman — March 30, 2011 @ 1:38 pm

    • Hi NickiAs a tiny part of my role as e-Learning Champion’ I produce a mohtnly bulletin for schools, I thought you might be interested to see what I have put in the January bulletin:‘Lordy’s Links’Again Paul shares 3 web links which relate to ICT in education. – Finally, if you did not see The Geeky ICT Teacher’ at BETT this year (aka Nicki Maddams), you must visit her website. Back to gaming again! This time it’s a PC interface, Nicki shows you how to create a simple game with ‘Kodu’. There are full lesson plans in her Resources – KS3 section of the site and also some for our old favourite ‘Scratch’. A great site for the latest innovative ideas.

      Comment by Kelly — May 15, 2013 @ 5:10 pm

  18. Check your ip address below
    What is your ip address

    Comment by flashflex — October 22, 2011 @ 8:09 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Customized Silver is the New Black Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 28 other followers

%d bloggers like this: