2

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.

Pro.Hessam
  • 819
  • 3
  • 11
  • 26

3 Answers3

5

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Thanks for your response. Now I'm using DatagramSocket in a networking program. But again, It fails. I've asked a new question which you can find it here: http://stackoverflow.com/questions/6579350/sending-packets-to-255-255-255-255-by-java-datagramsocket-fails . – Pro.Hessam Jul 05 '11 at 09:15
1

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

Declan Cook
  • 6,066
  • 2
  • 35
  • 52
1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483