Reputation: 83
I'm trying to send a broadcast from java on my mac. This seems like it should work, but I'm getting a SecurityException. I've verified that there isn't a SecurityManager installed, and tried running my class using sudo.
The code:
public static void main(String[] args) throws Exception{
SocketAddress sockAddr = new InetSocketAddress("192.168.0.255",
4000);
ByteBuffer bb = ByteBuffer.allocate(10);
bb.put(new Byte("1"));
DatagramChannel channel = DatagramChannel.open();
channel.send(bb, sockAddr);
}
The exception:
Exception in thread "main" java.net.SocketException: Permission denied
at sun.nio.ch.DatagramChannelImpl.send0(Native Method)
at sun.nio.ch.DatagramChannelImpl.sendFromNativeBuffer(DatagramChannelImpl.java:301)
at sun.nio.ch.DatagramChannelImpl.send(DatagramChannelImpl.java:281)
at sun.nio.ch.DatagramChannelImpl.send(DatagramChannelImpl.java:250)
at Test.main(Test.java:15)
Upvotes: 2
Views: 1019
Reputation: 94829
Having done a little googling, you need to tell the socket that the DatagramChannel is using that it's a broadcast Channel using the code:
channel.socket().setBroadcast(true);
I think it's just that you need to set the broadcast socket option on the 'channel', which is the underlying O/S socket. Evidently this will be doable from the channel level once java7 comes out, but currently you need to access the DatagramSocket to set the parameter.
Upvotes: 3
Reputation: 147154
That's SocketException
not SecurityException
(or AccessControlException
). Seems that the OS isn't allowing your process to send that datagram.
Upvotes: 0