An exception throws when I try to make a Socket to 255.255.255.255
It's my first time programming network in java. I want to use it in a small network. I was looking for a way to send to somehow broadcast to all nodes in the whole networking. To let them know of my existence. Someone开发者_运维知识库 told me send data packets to 255.255.255.255 so anyone in the network will receive it.
So I wrote this piece of code:
try{
Socket socket= new Socket("255.255.255.255", 3550);
}catch(Exception e){
System.out.println("oops! " + e.getMessage());
}
But, unfortunately it prints:
oops! Permission denied
When I change "255.255.255.255" to "192.168.1.3", which is my mate's IP address, it works fine. Also when I change "255.255.255.255" to "192.168.1.255", which according to ifconfig is my broadcast address, I get an Exception with the same message.
I'm in a adhoc network.
My OS is MAC OS X 10.6 My mate is in Windows Vista Home Premium Service Pack 1.Please make it simple, I'm a newbie :)
Thanks in advance.
Socket()
creates a stream (TCP) socket. You can't broadcast a stream. You need a datagram socket (UDP), so you should use the more specialized class DatagramSocket()
instead.
I believe that Java TCP sockets only support Unicast communication, where as you want to be using datagram sockets.
http://download.oracle.com/javase/1.4.2/docs/api/java/net/DatagramSocket.html
Trying to connect a TCP Socket to the non-existent IP address 255.255.255.255 (a) is impossible and (b) doesn't send anything anywhere. It isn't the same thing as sending a UDP datagram via a DatagramSocket with a target address of 255.255.255.255, which is what you were advised to do.
精彩评论