Gets the broadcast address of an IP address

S

Sai Hl

Hi Ruby communauty. I am trying to broadcast a message using UDPSocket
on destination port 10000. My code is:

client = UDPSocket.new
client.connect Socket.gethostname, 10000
client.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
client.send data, 0

But my packet is not a broadcast, its address is the same as my host:
192.168.0.101

In order to do so on the external interface of my system (named en0), I
had remplaced this:
client.connect Socket.gethostname, 10000
by this:
client.connect "192.168.0.255", 10000

And now this is working. But is there a way to get automatically the
"192.168.0.255" address thanks to a Ruby method? I know I can get my IP
with IPSocket.getaddress(Socket.gethostname) but I don't see any way to
gets its broadcast address.

Thanks
 
E

Eleanor McHugh

Hi Ruby communauty. I am trying to broadcast a message using
UDPSocket
on destination port 10000. My code is:

client = UDPSocket.new
client.connect Socket.gethostname, 10000
client.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
client.send data, 0

But my packet is not a broadcast, its address is the same as my host:
192.168.0.101

In order to do so on the external interface of my system (named
en0), I
had remplaced this:
client.connect Socket.gethostname, 10000
by this:
client.connect "192.168.0.255", 10000

And now this is working. But is there a way to get automatically the
"192.168.0.255" address thanks to a Ruby method? I know I can get
my IP
with IPSocket.getaddress(Socket.gethostname) but I don't see any way
to
gets its broadcast address.

Thanks


The simplest way to do it is to use a regex to change the last term in
the quad:

IPSocket.getaddress(Socket.gethostname).gsub!(/.\d{1,3}$/, '.255')


Ellie

Eleanor McHugh
Games With Brains
http://slides.games-with-brains.net
 
B

Brian Candler

Eleanor said:
True, but I'm not sure the general case is so easy on the eye ;p

This is messier than it should be, but:

require 'ipaddr'
n = IPAddr.new("192.168.0.101/24")
p n | (~n.instance_variable_get:)@mask_addr) & IPAddr::IN4MASK)

Or maybe you could just broadcast to the all-ones address
(255.255.255.255)
 
S

Sai Hl

Brian said:
This is messier than it should be, but:

require 'ipaddr'
n = IPAddr.new("192.168.0.101/24")
p n | (~n.instance_variable_get:)@mask_addr) & IPAddr::IN4MASK)

Or maybe you could just broadcast to the all-ones address
(255.255.255.255)

Yes, I had use the broadcast address ;)
Finaly it's simple and efficient. But I think I will try your first
solution after to.

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top