I am trying to create a small Application which reads data from the Serial-/Com-Port and broadcasts the data to my network using port 15000
.
Everything works fine on Windows and Linux (using Mono) but I get a Socket Exception
on macOS with the following message: Access denied
I tried to run my Application with elevated permissions:
sudo mono ./SerialMonitor.exe
But that doesn't work too.
Is there any way to get rid of that exception? And why does it work without any issues on Windows and Linux?
Here is my code:
using System;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SerialMonitor
{
class MainClass
{
static SerialPort mSerial = new SerialPort();
static String[] mSerialPorts;
static UdpClient mNetwork;
static IPEndPoint mIP;
static String mData = "";
public static void Main(string[] args)
{
mNetwork = new UdpClient();
mIP = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 15000);
mSerialPorts = SerialPort.GetPortNames();
Console.WriteLine("Select a serial port:");
if (mSerialPorts.Length == 0)
{
Console.WriteLine("No serial ports available!");
return;
}
for (int i = 0; i < mSerialPorts.Length; i++)
{
Console.WriteLine(i + 1 + ": " + mSerialPorts[i]);
}
Console.Write("Selection: ");
int selection = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Selected port: " + mSerialPorts[selection - 1]);
mSerial.PortName = mSerialPorts[selection - 1];
mSerial.BaudRate = 9600;
mSerial.NewLine = "\r\n";
mSerial.Open();
mSerial.DiscardInBuffer();
Console.WriteLine("\nData:");
while (true)
{
try
{
MainClass.mData = mSerial.ReadLine();
Console.WriteLine(MainClass.mData);
byte[] bytes = Encoding.ASCII.GetBytes(MainClass.mData);
mNetwork.Send(bytes, bytes.Length, mIP);
}
catch(SocketException ex)
{
Console.WriteLine("\nNETWORK ERROR: " + ex.Message);
Console.Read();
return;
}
catch (Exception ex)
{
Console.WriteLine("\nERROR: " + ex.Message);
Console.Read();
return;
}
}
}
}
}
I am using Visual Studio Community 2017 for Mac
Version 7.1 (build 1297)
Mono 5.2.0.215 (d15-3/da80840) (64-bit)
Project configuration:
.NET Framework 4.6.1
x86
If you want to send broadcast messages across your local subnet (or broadcasts in general) you have to enable broadcasts on your socket with:
mNetwork.EnableBroadcast = true;
Reference:
https://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient(v=vs.110).aspx
http://answers.unity3d.com/questions/248494/socket-exception-access-denied.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With