From: Reid Thompson Date: 2007-06-15T02:22:21+09:00 Subject: Re: How can I get the local machine's netmask programmatically? On Fri, 2007-06-15 at 01:48 +0900, list.rb@gmail.com wrote: > I spent quite a bit of time last night trying to figure this out to no > avail. > > Reid, how long did it take you to come up with this? Could anyone > without C experience figured this out? > > > > > see if this works....???? > > > > rthompso@shienar ~ $ cat getnetmask.rb > > require 'rubygems' > > require "inline" > > > > class NetMask > > inline do |builder| > > builder.include '' > > builder.include '' > > builder.include '' > > builder.include '' > > builder.include '' > > builder.c " > > > > char * nmask() { > > int fd; > > struct ifreq ifr; > > > > fd = socket(AF_INET, SOCK_DGRAM, 0); > > ifr.ifr_addr.sa_family = AF_INET; > > strncpy(ifr.ifr_name, \"eth0\", IFNAMSIZ-1); > > ioctl(fd, SIOCGIFNETMASK, &ifr); > > close(fd); > > > > return (char *)inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr); > > }" > > end > > end > > > > nm = NetMask.new() > > nmaa = nm.nmask() > > puts nmaa > > > > rthompso@shienar ~ $ ruby getnetmask.rb > > 255.255.255.0 > 1) I was previously aware of RubyInline -- so didn't have to 'find/research' it 2) I knew that getting the info in C code was doable 3) I googled for examples of getting socket info 4) it took me about 15 minutes probably 4a) I think a non-C programmer could have figured it out in time I basically copied the C RubyInline example ( the factorial one ) and pasted in the socket code. The gotcha's would probably have been a)figuring out to use the builder.include, described in the C++ example, to get the header files included b)getting rid of a warning message due to the original C code not casting to (char *) the return value of inet_ntoa() 5) Ruby's various socket classes probably provide access to the same info - but I couldn't find out how to get at it ( like you, I spent waaaay more time trying to find a pure ruby way of getting the info than coding the example ) i.e. Ruby's Socket class has a getsockname which returns the struct sockaddr packed into a string -- It may have all the info needed, but I'm not familiar enough with unpacking a sockaddr structure to try to figure it out ( or unpacking anything in Ruby for that matter :) ).