Search code examples
iplocalgethostbynameifconfigipconfig

how to write a program to report the local IP address such as 192.168.1.102?


since my Linksys router doesn't assign a fixed local IP to the computers (PC and Mac and Linux), i'd like to write a script so that every minute, the computers will update to each other so that

http://localhost/list.html

on each machine will contain a list of names of all PC and Mac and a link to their apache server (pointing to http://192.168.1.102, etc)

it looks like a way to find out the local IP address is by ipconfig on PC, and ifconfig on the Mac and Linux, and to do it programmatically, it will be gethostbyname().

But I tried on Ruby, that

irb(main):001:0> require 'socket'
=> true

irb(main):002:0> p Socket::gethostbyname("localhost")
["Core2Duo", [], 2, "\177\000\000\001"]

irb(main):005:0> p Socket::gethostbyname("core2duo")
["Core2Duo", [], 2, "\300\250\001g"]
=> nil

and ipconfig actually shows

IPv4 Address. . . . . . . . . . . : 192.168.1.103

so is this the right way to do it? I can hack it by executing "ipconfig" in Ruby and use regular expression to get the result, but would be nice to do it using a more standard way.


Solution

  • Socket::getaddrinfo might be more of what you're looking for:

    Socket::getaddrinfo('localhost', 'http')
    [["AF_INET", 80, "localhost", "127.0.0.1", ...]]
    
    Socket::getaddrinfo('core2duo', 'http')
    [["AF_INET", 80, "Core2Duo", "192.168.1.103", ...]]
    

    Or, you might just try:

    Socket::getaddrinfo('core2duo', 'http')[0][3]
    "192.168.1.103"