SocketException proper handling in C# - c#

I'm currently writing a code in C# and it needs to communicate with a program written in VB6 through sockets. <br/>
When the VB6 program is not running, my C# program throws a SocketException.
What I did was catch the exception but I noticed that it will keep throwing that exception until the VB6 program runs again.<br/><br/>
The ReceiveFrom(...) method is in an infinite loop so when the VB6 program runs again, it can receive data.<br/><br/>
I wonder if there's a better way to handle this.
the C# code looks like this...
internal class SocketConnection : Connection
{
private Socket socket;
private EndPoint localEndPoint;
private IPEndPoint remoteIPEndPoint;
internal SocketConnection(int localPortNumber, IPAddress remoteIPAddress, int remotePortNumber)
{
IPEndPoint localIPEndPoint = new IPEndPoint(
GetLocalIPAddress(),
localPortNumber);
socket = new Socket(
localIPEndPoint.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);
socket.Bind(localIPEndPoint);
localEndPoint = (EndPoint)localIPEndPoint;
Thread receiver = new Thread(() => Receive());
receiver.Start();
remoteIPEndPoint = new IPEndPoint(remoteIPAddress, remotePortNumber);
}
private void Receive()
{
byte[] msg = new Byte[256];
while (true)
{
try
{
socket.ReceiveFrom(msg, ref localEndPoint);
buffer = Encoding.ASCII.GetString(msg).TrimEnd('\0');
}
catch (SocketException)
{
buffer = string.Empty;
}
}
}
private IPAddress GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip;
}
}
throw new Exception("Local IP Address Not Found!");
}
protected override void Interrogate(string message)
{
socket.SendTo(Encoding.ASCII.GetBytes(message), remoteIPEndPoint);
}
}

Before calling ReceiveFrom you should check that there is something to read in the socket :
int available = socket.Available;
if (available > 0)
{
socket.ReceiveFrom(msg, 0, Math.Min(msg.Length, available), SocketFlags.None, ref localEndPoint);
buffer = Encoding.ASCII.GetString(msg).TrimEnd('\0');
}

Related

Simple socket server in Unity

I want to use a C# plugin in my Unity project. That plugin should act as a server which will get values from a client so that I'd be able to use those values for further processing.
The issue is that the server has infinite loop. And infinite loops cause Unity to hang. How to handle this?
EDIT: I'm attaching a code snippet of server program. In my opinion, there are 2 points which may be causing problem. The infinite loops and the point where program is suspended as commented in code:
void networkCode()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 1755);
// Create a TCP/IP socket.
listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
// Program is suspended while waiting for an incoming connection.
Debug.Log("HELLO"); //It works
handler = listener.Accept();
Debug.Log("HELLO"); //It doesn't work
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
System.Threading.Thread.Sleep(1);
}
System.Threading.Thread.Sleep(1);
}
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
EDIT: After help from #Programmer, the C# plugin is complete. But Unity is not reading the correct values. I'm attaching the Unity side code:
using UnityEngine;
using System;
using SyncServerDLL; //That's our library
public class receiver : MonoBehaviour {
SynchronousSocketListener obj; //That's object to call server methods
// Use this for initialization
void Start() {
obj = new SynchronousSocketListener ();
obj.startServer ();
}
// Update is called once per frame
void Update() {
Debug.Log (obj.data);
}
}
I have tested SynchronousSocketListener class thoroughly in Visual Studio. It is giving good results there.
Use Thread to do your server Listen and read and write actions.
You can declare socket and other networkstream objects as public then initialize them in a thread function.
Unity does not work well with while loops in Threads and may freeze sometimes, but you can fix that by adding System.Threading.Thread.Sleep(1); in your while loop where you are reading or waiting for data to arrive from socket.
Make sure to stop the Thread in OnDisable() function. Do NOT access Unity API from the new Thread function. Just do only the socket stuff there and return the data to a public variable.
System.Threading.Thread SocketThread;
volatile bool keepReading = false;
// Use this for initialization
void Start()
{
Application.runInBackground = true;
startServer();
}
void startServer()
{
SocketThread = new System.Threading.Thread(networkCode);
SocketThread.IsBackground = true;
SocketThread.Start();
}
private string getIPAddress()
{
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
Socket listener;
Socket handler;
void networkCode()
{
string data;
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// host running the application.
Debug.Log("Ip " + getIPAddress().ToString());
IPAddress[] ipArray = Dns.GetHostAddresses(getIPAddress());
IPEndPoint localEndPoint = new IPEndPoint(ipArray[0], 1755);
// Create a TCP/IP socket.
listener = new Socket(ipArray[0].AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
keepReading = true;
// Program is suspended while waiting for an incoming connection.
Debug.Log("Waiting for Connection"); //It works
handler = listener.Accept();
Debug.Log("Client Connected"); //It doesn't work
data = null;
// An incoming connection needs to be processed.
while (keepReading)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
Debug.Log("Received from Server");
if (bytesRec <= 0)
{
keepReading = false;
handler.Disconnect(true);
break;
}
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
System.Threading.Thread.Sleep(1);
}
System.Threading.Thread.Sleep(1);
}
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
void stopServer()
{
keepReading = false;
//stop thread
if (SocketThread != null)
{
SocketThread.Abort();
}
if (handler != null && handler.Connected)
{
handler.Disconnect(false);
Debug.Log("Disconnected!");
}
}
void OnDisable()
{
stopServer();
}

UDP sending / receiving on a free port

In a project there is a device that listens on a specific UDP port and answers to the senders port.
For the sender and receiver I want the system to choose a free port, so I have the following code:
[Please excuse the vast masses of code, but this is the smallest example to show what behaviour occurs]
Sending code:
public class UdpSender
{
public int Port = 0; // some initially random port
public UdpClient UdpServer { get; set; }
public UdpSender()
{
UdpServer = CreateUdpClient();
// save the portnumber chosen by system to reuse it
Port = ((IPEndPoint)(UdpServer.Client.LocalEndPoint)).Port;
}
private UdpClient CreateUdpClient()
{
if (UdpServer != null)
{
UdpServer.Close();
}
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Port);
var udpServer = new UdpClient();
udpServer.ExclusiveAddressUse = false;
udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer.Client.Bind(localEndPoint);
return udpServer;
}
public void Send(byte[] arr)
{
UdpServer = CreateUdpClient();
int remotePortNumber = 6565;
var remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, remotePortNumber);
try
{
UdpServer.Send(arr, arr.Length, remoteEndPoint);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
UdpServer.Close();
}
}
Receiving code:
public class UDPListener
{
private static int portNumber;
private UdpClient udpClient = null;
public List<DeviceData> DeviceList = new List<DeviceData>();
public UDPListener(int port)
{
portNumber = port;
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, portNumber);
udpClient = new UdpClient();
udpClient.ExclusiveAddressUse = false;
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.Client.Bind(localEndPoint);
udpClient.Client.ReceiveBufferSize = 1 << 23;
}
public void StartListening()
{
this.udpClient.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, portNumber);
byte[] bytes = udpClient.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
DeviceList.Add(new DeviceData(message));
StartListening();
}
}
Bringing it together:
public class DeviceFinder
{
public IEnumerable<DeviceData> Find()
{
var sender = new UdpSender();
int port = sender.Port;
var listener = new UDPListener(port);
listener.StartListening();
sender.Send(new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 });
System.Threading.Thread.Sleep(5000); // wait some time for answers
return listener.DeviceList;
}
}
The Receive method is never called with this approach. But in Wireshark, I can see an answer coming from the device.
What is wrong about this approach?
Before using this approach, I have used a fixed port and the call to CreateUdpClient was added also. Seems to have something to with that, but I cannot figure it out.
Before I just created a UdpClient with the fixed port just inside the receive / send method.
The previous version can be seen in this question. This works perfectly. But I fear if the fixed port is already in use, it does not work, hence this new approach.
Just specify zero as your own port number. The system will allocate one when you bind or send. The source port number will accompany the datagram to the peer, who should reply to it.

C# UDP Server Asynchronous Multiple Clients | SocketException When Client Disconnect

I've been working on a socket server program in C# (I was inspired from this post) and my problem is that when a client disconnects an exception "An existing connection was forcibly closed by the remote host" appears when the call EndReceiveFrom() and returns 0, the ref clientEP becomes the client normally close. I don't understand why my DoReceiveFrom() function is called if there is nothing to read. I probably missed something. What is wrong ?
Problem appear there :
int dataLen = this.serverSocket.EndReceiveFrom(iar, ref clientEP);
The full source code:
class UDPServer
{
private Socket serverSocket = null;
private List<EndPoint> clientList = new List<EndPoint>();
private List<Tuple<EndPoint, byte[]>> dataList = new List<Tuple<EndPoint, byte[]>>();
private byte[] byteData = new byte[1024];
private int port = 4242;
public List<Tuple<EndPoint, byte[]>> DataList
{
private set { this.dataList = value; }
get { return (this.dataList); }
}
public UDPServer(int port)
{
this.port = port;
}
public void Start()
{
this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
this.serverSocket.Bind(new IPEndPoint(IPAddress.Any, this.port));
EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);
}
private void DoReceiveFrom(IAsyncResult iar)
{
try
{
EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
int dataLen = this.serverSocket.EndReceiveFrom(iar, ref clientEP);
byte[] data = new byte[dataLen];
Array.Copy(this.byteData, data, dataLen);
if (!this.clientList.Any(client => client.Equals(clientEP)))
this.clientList.Add(clientEP);
EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);
DataList.Add(Tuple.Create(clientEP, data));
}
catch (ObjectDisposedException)
{
}
}
public void SendTo(byte[] data, EndPoint clientEP)
{
try
{
this.serverSocket.SendTo(data, clientEP);
}
catch (System.Net.Sockets.SocketException)
{
this.clientList.Remove(clientEP);
}
}
public void SendToAll(byte[] data)
{
foreach (var client in this.clientList)
{
this.SendTo(data, client);
}
}
public void Stop()
{
this.serverSocket.Close();
this.serverSocket = null;
this.dataList.Clear();
this.clientList.Clear();
}
}
Exception:
An existing connection was forcibly closed by the remote host
Update:
I tried to run my client (netcat) on another pc and the exception no longer appears, even when SendTo(), which is also problematic to delete my client in my clientList.
I still do not understand what is happening.
Everything is as it should be.
This is the way all Async methods work: you invoke BeginDo() and pass into it your implementation of AsyncCallback delegate (in your example that's DoReceiveFrom). You implementation starts executing immediately after that - BeginDo() is not a blocking call.
Inside your implementation, you must call EndDo(), which will block until one of two things happen: the object, on which you invoked BeginDo(), actually does something, or it throws an exception doing it. As it does in your case when client disconnects.
The source on the Async method.
What you need to do for the whole thing to work is
Make sure that you handle that client-disconnected exception properly
Make sure that you call BeginReceiveFrom regardless of the way EndReceiveFrom finishes. And preferably, call BeginReceiveFrom immediately after you call EndReceiveFrom. This is needed because while you server is in-between those calls, it does not actually listen to the socket.
I would put another try-catch around EndReceiveFrom.
UPDATE:
private void DoReceiveFrom(IAsyncResult iar)
{
try
{
EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
int dataLen = 0;
byte[] data = null;
try
{
dataLen = this.serverSocket.EndReceiveFrom(iar, ref clientEP);
data = new byte[dataLen];
Array.Copy(this.byteData, data, dataLen);
}
catch(Exception e)
{
}
finally
{
EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);
}
if (!this.clientList.Any(client => client.Equals(clientEP)))
this.clientList.Add(clientEP);
DataList.Add(Tuple.Create(clientEP, data));
}
catch (ObjectDisposedException)
{
}
}

Send text file directly to network printer

I have currently-working code which sends raw data to a printer by writing a temporary file, then using File.Copy() to send it to the printer. File.Copy() supports both local ports, like LPT1 and shared printers like \\FRONTCOUNTER\LabelPrinter.
However, now I'm trying to get it working with a printer that's directly on the network: 192.168.2.100, and I can't figure out the format to use.
File.Copy(filename, #"LPT1", true); // Works, on the FRONTCOUNTER computer
File.Copy(filename, #"\\FRONTCOUNTER\LabelPrinter", true); // Works from any computer
File.Copy(filename, #"\\192.168.2.100", true); // New printer, Does not work
I know it's possible to "Add a printer" from each computer, but I'm hoping to avoid that - the second line of code above works from any computer on the network automatically, with no configuration required. I also know it's possible to P/Invoke the windows print spooler, and if that's my only option I may take it, but that's much more code overhead than I'd like to have.
Ideally, someone will have either a way to make File.Copy() work or a similar C# statement which will accept a network IP.
You can use sockets and send the data straight to that IP address. Should pretty much be the same as File.Copy. I just tried it out and that worked.
I just sent some text but here is the code that I used
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.NoDelay = true;
IPAddress ip = IPAddress.Parse("192.168.192.6");
IPEndPoint ipep = new IPEndPoint(ip, 9100);
clientSocket.Connect(ipep);
byte[] fileBytes = File.ReadAllBytes("test.txt");
clientSocket.Send(fileBytes);
clientSocket.Close();
try this code:
public class PrintHelper
{
private readonly IPAddress PrinterIPAddress;
private readonly byte[] FileData;
private readonly int PortNumber;
private ManualResetEvent connectDoneEvent { get; set; }
private ManualResetEvent sendDoneEvent { get; set; }
public PrintHelper(byte[] fileData, string printerIPAddress, int portNumber = 9100)
{
FileData = fileData;
PortNumber = portNumber;
if (!IPAddress.TryParse(printerIPAddress, out PrinterIPAddress))
throw new Exception("Wrong IP Address!");
}
public PrintHelper(byte[] fileData, IPAddress printerIPAddress, int portNumber = 9100)
{
FileData = fileData;
PortNumber = portNumber;
PrinterIPAddress = printerIPAddress;
}
/// <inheritDoc />
public bool PrintData()
{
//this line is Optional for checking before send data
if (!NetworkHelper.CheckIPAddressAndPortNumber(PrinterIPAddress, PortNumber))
return false;
IPEndPoint remoteEP = new IPEndPoint(PrinterIPAddress, PortNumber);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.NoDelay = true;
connectDoneEvent = new ManualResetEvent(false);
sendDoneEvent = new ManualResetEvent(false);
try
{
client.BeginConnect(remoteEP, new AsyncCallback(connectCallback), client);
connectDoneEvent.WaitOne();
client.BeginSend(FileData, 0, FileData.Length, 0, new AsyncCallback(sendCallback), client);
sendDoneEvent.WaitOne();
return true;
}
catch
{
return false;
}
finally
{
// Shutdown the client
this.shutDownClient(client);
}
}
private void connectCallback(IAsyncResult ar)
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
// Signal that the connection has been made.
connectDoneEvent.Set();
}
private void sendCallback(IAsyncResult ar)
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
// Signal that all bytes have been sent.
sendDoneEvent.Set();
}
private void shutDownClient(Socket client)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
Network Helper class:
public static class NetworkHelper
{
public static bool CheckIPAddressAndPortNumber(IPAddress ipAddress, int portNumber)
{
return PingIPAddress(ipAddress) && CheckPortNumber(ipAddress, portNumber);
}
public static bool PingIPAddress(IPAddress iPAddress)
{
var ping = new Ping();
PingReply pingReply = ping.Send(iPAddress);
if (pingReply.Status == IPStatus.Success)
{
//Server is alive
return true;
}
else
return false;
}
public static bool CheckPortNumber(IPAddress iPAddress, int portNumber)
{
var retVal = false;
try
{
using (TcpClient tcpClient = new TcpClient())
{
tcpClient.Connect(iPAddress, portNumber);
retVal = tcpClient.Connected;
tcpClient.Close();
}
return retVal;
}
catch (Exception)
{
return retVal;
}
}
}

building a C# asynchronous TCP proxy server

I am attempting to build a simple C# TCP proxy for my business so I can block certain websites from my employees. All is well except I am having trouble seeing what website the user is trying to visit... I can see that the user has connected to my proxy server so I know I am getting connections but the OnRecieve callback isn't even firing. Am I reading from the socket wrong?
Here is my code:
internal class AsyncState
{
public const int BufferSize = 4096;
public byte[] Buffer = new byte[AsyncState.BufferSize];
public Socket Socket;
public StringBuilder Content = new StringBuilder();
}
private void OnLoad(object sender, EventArgs e)
{
IPAddress[] addressCollection = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ipAddress in addressCollection)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
localEndPoint = new IPEndPoint(ipAddress, 8080);
Console.WriteLine("Local IP address found... " + localEndPoint.ToString());
break;
}
}
isListening = true;
thread = new Thread(new ThreadStart(
delegate()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(localEndPoint);
serverSocket.Listen(10);
while (isListening)
{
resetEvent.Reset();
Console.WriteLine("Waiting for clients...");
serverSocket.BeginAccept(new AsyncCallback(OnAccept), serverSocket);
resetEvent.WaitOne();
}
}));
thread.Start();
}
}
private void OnAccept(IAsyncResult result)
{
resetEvent.Set();
Socket clientSocket = (result.AsyncState as Socket).EndAccept(result);
Console.WriteLine("Client has connected... " + clientSocket.RemoteEndPoint.ToString());
AsyncState state = new AsyncState();
state.Socket = clientSocket;
state.Socket.BeginReceive(state.Buffer, 0, AsyncState.BufferSize, SocketFlags.None, new AsyncCallback(OnRecieve), state);
}
private void OnRecieve(IAsyncResult result)
{
AsyncState state = result.AsyncState as AsyncState;
int totalRead = state.Socket.EndReceive(result);
if (totalRead > 0)
{
state.Content.Append(Encoding.ASCII.GetString(state.Buffer, 0, totalRead));
state.Socket.BeginReceive(state.Buffer, 0, AsyncState.BufferSize, SocketFlags.None, new AsyncCallback(OnRecieve), state);
}
else
{
if (state.Content.Length > 1)
Console.WriteLine("Message recieved from client... " + state.Content.ToString());
state.Socket.Close();
}
}
Building a well working proxy is no simple task as you will have to understand and handle HTTP etc. in both directions...
I would recommend to either use an existing library for that OR some configurable proxy...
http://www.mentalis.org/soft/projects/proxy/ (with source)
http://sourceforge.net/p/portfusion/home/PortFusion/ (with source)
http://www.wingate.com/
http://www.squid-cache.org/
REMARK:
I don't know in which jurisdiction you are but using such technology without knowledge/consent of employees can in some places be a problem...
Another point: Instead of using such methods I would tell the employee to stop abusing the internet connection of the company 1-3 times and if that doesn't work I would rather fire that person... such employees is not only abusing the internet connection of the company but in worstcase is putting the company at risk (virus/trojan etc.) and also defrauding the company (if he does this in work hours)...

Categories