Socket exception: Access denied

Hi all,

I want to use System.Net and System.Net.Sockets to broadcast UDP packets on my LAN, however, on sending the data on the socket I get an “Access denied” exception. I’m new to .Net and C#, am I doing something wrong programming wise, or is this perhaps a licensing limitation (I’m using an expired unity pro trial license, which I believe reverts to the same functionality as the free version?)

Here’s the code:

using System.Net;
using System.Net.Sockets;
using System.Text;
Boolean exception_thrown = false;
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse("192.168.0.255");
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 25000);
string formattedString;
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
formattedString = String.Format("sending to address: {0} port: {1}", sending_end_point.Address, sending_end_point.Port); 
try {
Debug.Log(send_buffer);
sending_socket.SendTo(send_buffer, sending_end_point);
} catch (Exception send_exception ) {
exception_thrown = true;
formattedString = String.Format("Exception {0}", send_exception.Message);
Debug.Log(formattedString);
}

I just tried your code together with one of my old UDP listener (written in Delphi) and i receive the text i send out to my local broadcast address. Are you sure that you build to standalone? It won’t work in a web build of course…

edit
I’ve played a bit with some parameters and i’ve found out that you can’t send broadcasts to the general broadcast address unless you set EnableBroadcast to true.

So just set the property to true right after you created your socket:

Socket sending_socket = new Socket(/*[...]*/);
sending_socket.EnableBroadcast = true;
IPAddress send_to_address = IPAddress.Parse("255.255.255.255");
// [...]

On Mac, you have to run Unity with elevated permissions to host sockets. Try the following command:

sudo /Applications/Unity/Unity.app/Contents/MacOS/Unity

1024 @LupaNafas