An exception throws when I try to make a Socket to 255.255.255.255

☆樱花仙子☆ 提交于 2020-01-02 19:08:31

问题


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.


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/6572715/an-exception-throws-when-i-try-to-make-a-socket-to-255-255-255-255

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!