error opening socket in program on network location - c#

I develop software from a network location. Until recently this works without problems. But after the last Windows 10 update (may 2018) something changed. Programs still run from this location but when I try to open a socket I get the error 'invalid argument (10022)'. The code is so basic:
Socket s;
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Running it from a local disk doesn't produce the error.
A sample program with with a single button will generate this error condition.
private void button1_Click(object sender, EventArgs e)
{
Socket s;
try
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
catch (Exception error)
{
MessageBox.Show("Error : " + error.Message);
return;
}
MessageBox.Show("Oke");
}
Any thoughts how to proceed?

Related

System.Net.SocketException in Socket.Connect - (0x80004005) Unknown host

I am facing some problems with connect method while attempting to connect to a remote host. The main task deals with an industrial device which accepts TCP connections. The PC has two network cards with different networks families. It seems that the connect method is not able to reach the correct IP address. In fact, if I try to unplug the other network, everything works properly. Variables IPAddress and Port are set from the software. The error is:
System.NetSockets.SocketException (0x80004005): Unknown host at
System.Net.Dns.InternalGetHostEntry()
Below the code:
public void Connect()
{
int port;
try
{
int.TryParse(Port, out port);
socketMarking = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs telnetSocketAsyncEventArgs = new SocketAsyncEventArgs();
telnetSocketAsyncEventArgs.RemoteEndPoint = new IPEndPoint(Dns.GetHostEntry(IPAddress.Trim()).AddressList[0].MapToIPv4(), port);
telnetSocketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(telnetSocketAsyncEventArgs_Completed);
socketMarking.ReceiveTimeout = 3000;
socketMarking.Connect(IPAddress, port);
streamWrite = new NetworkStream(socketMarking);
Connected = true;
}
catch (SocketException ex)
{
main.AddMessage("Socket error on IP " + IPAddress + ":" + Port + "-->"+ex.ToString());
}
}
Another discussion point is that debugging on two different PC everything works, but only on that one I have this kind of problem. All firewalls and possible protections are disabled.

WSAENETDOWN SocketException on a FEZ Spider kit

I'm trying to write a TCP server in .NETMF 4.3 for my FEZ Spider kit.
public partial class Program
{
void ProgramStarted()
{
ethernetJ11D.NetworkInterface.Open();
ethernetJ11D.UseStaticIP("192.168.0.8", "255.255.255.0", "192.168.0.1");
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint endPoint = new IPEndPoint(IPAddress.Any, 7777);
serverSocket.Bind(endPoint);
serverSocket.Listen(10);
new Thread(() =>
{
while (true)
{
Debug.Print("Network up: " + ethernetJ11D.IsNetworkUp);//true
Debug.Print("Network connected: " + ethernetJ11D.IsNetworkConnected);//true
System.Net.Sockets.Socket clientSocket = serverSocket.Accept();//exception!
new Thread(new Request(clientSocket).Process);
}
}).Start();
}
The serverSocket.Accept method throws a SocketException with error code 10050. This page says it's WSAENETDOWN: Network is down. However the ethernetJ11D's properties state that the connection is up and I can ping the device without any problems. What am I doing wrong?
EDIT
When I tried running the following client I got the same exception on the socket.Connect call.
ethernetJ11D.NetworkInterface.Open();
ethernetJ11D.UseStaticIP("192.168.0.8", "255.255.255.0", "192.168.0.1");
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("192.168.0.5"), 7777);
socket.Connect(endpoint);
Debug.Print("connected");
byte[] msg = new byte[] { 7, 77, 222 };
socket.Send(msg);
EDIT 2
I've tried to implement the UDP client instead. It doesn't work either.
I've solved the problem:
Change IPAddress.Any to a static IP,e.g. IPAddress.Parse("192.168.0.8").
Delay Bind by adding Thread.Sleep(3000) right before it. It seems that the interface's network settings configuration takes some time.

Other computers can't connect my program

I'm building a C# chat program, yet I'm facing a problem with outside connection.
When the same computer connects both as server and as client, there seems to be no problem, yet when I try to host the connection on one computer, the other can't connect as a client.
here's the relevant code:
class Server:
public void Connect(string ipAddr, string port)
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, Convert.ToInt32(port));
server.Bind(ipLocal);//bind to the local IP Address...
server.Listen(5);//start listening...
// create the call back for any client connections...
server.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
public void Disconnect()
{
server.Close();
server = null;
tempSocket = null;
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
if (server != null)
{
tempSocket = server.EndAccept(asyn);
WaitForData(tempSocket);
server.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
}
catch (ObjectDisposedException)
{
Debugger.Log(0, "1", "OnClientConnect: Socket has been closed.");
}
catch (Exception e)
{
MessageBox.Show(e.Message, "OnClientConnect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Client class:
public void Connect(string ipAddr, string port)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ipAddr), Convert.ToInt32(port));
client.Connect(ipe);
clientListener = new Thread(OnDataReceived);
isEndClientListener = false;
clientListener.Start();
}
I have no idea what's wrong here. Hope you can tell me what's wrong.
Your issue is probably not code related. In order for other people outside your network to conenect to you, you need to port forward the port that you are connecting through on your router. You can find many tutorials here. You may also check to see if your connection is open through this tool.
From Wikipedia:
Port forwarding allows remote computers (for example, computers on the Internet) to connect to a specific computer or service within a private local-area network (LAN).
You must allow connections through your router to be able to connect to your chat server.
You need to give your computer a public IP address (maybe your router has this option) or implement port forwarding on your router.
A Public IP address would be the one of your router. Check out this site to find out your public IP whatismyipaddress.com. Your router can or cannot support the option to give its public IP address to your computer, however, your router should be able to do port forwarding. (Forwarding the data from a specific port to a specific computer, so when someone connects to your public IP. For example 93.93.93.93:3333 will be forwarded to your PC.)

Socket.Connect Throws and Error I can't catch

I apologize if this has been answered on SO. I looked but didn't find it. My situation is my customer can connect to their TCP server either by being on the local network, or coming in remotely via a Verizon modem. (I am using .NET 3.5 - C#)
When I connect from either of those, things are fine. But what if I am accidentally on the "wrong" network (ex: I am at Starbucks and logged onto their wireless network. I forget, thinking I am on the Verizon card, so, now I try to log in) The server refuses the connection. Fine. But my Try/Catch is not catching anything... it simply exits the routine (if I am calling it through threadpool) or it hangs if I call it directly.
Here is the code (it fails on: m_clientSocket.Connect(ipEnd) ):
tcpConnectionObject passedTCPObject = (tcpConnectionObject) obj;
if (checkNetStat(passedTCPObject) == false)
{
updateStatus(false);
return;
}
try
{
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(passedTCPObject.ipString);
int iPortNo = System.Convert.ToInt16(passedTCPObject.portString);
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
m_clientSocket.Connect(ipEnd);
if (m_clientSocket.Connected)
{
updateStatus(true);
//Wait for data asynchronously
WaitForData();
}
}
catch (SocketException e)
{
updateStatus(false);
return;
}
catch (Exception e)
{
updateStatus(false);
return;
}
updateStatus(true);
return ;
I call this from a Winform using the threadpool:
tcpConnectionObject passObject = new tcpConnectionObject(serverIP, serverPORT);
ThreadPool.QueueUserWorkItem(new WaitCallback(SRVR_CONNECT.connectToTCP), passObject);
This is called in the form's SHOW() method. When I do it like this, my form shows, but the status is never changed (which it should be by any result) If I put a debugger on it, and start stepping through the execution, I get to the Socket.Connect() and the debugger simply exits the mthod, and my form shows. I never hit any of my catches.
I have tried every error that Socket can generate, but it never catches anything. When I run my debugger, as soon as I hit that line, it exits my method, but there is no error that is catch-able.
If you really are waiting asynchronously (as you state in your comment), then you may be exiting the try/catch block before you actually get the exception.
It exits your method because you have a return statement inside of your catch block. You are telling it to return explicitly.
OK, I think Peter was on the right track. it seems like the debugger was simply skipping over my Connect line and moving on to the next line while waiting for the Socket.Connect() to finish (if that makes sense?)
Here's a change in the code that works... I move the packet creation, and the callback definition out of "WaitForData" and use the beginConnect method instead. Then I can set a timeout, which lets me know it fails -- so the code is changed to this:
try
{
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Cet the remote IP address
IPAddress ip = IPAddress.Parse(passedTCPObject.ipString);
int iPortNo = System.Convert.ToInt16(passedTCPObject.portString);
// Create the end point
ipEnd = new IPEndPoint(ip, iPortNo);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketPacket theSocPkt = new SocketPacket();
if (m_pfnCallBack == null)
{
m_pfnCallBack = new AsyncCallback(OnDataReceived);
}
// Give It 5 Seconds to connect
IAsyncResult result = socket.BeginConnect(ipEnd, m_pfnCallBack, theSocPkt);
bool success = result.AsyncWaitHandle.WaitOne(5000, true);
if (!success)
{
socket.Close();
throw new ApplicationException("Server Refused Connection");
}
// Success
updateStatus(true);
}
catch (SocketException e)
{
updateStatus(false);
return;
}
catch (Exception e)
{
updateStatus(false);
return;
}

How do I test my socket exception handling code?

I have the following code:
try
{
mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, serverPort);
mainSocket.Bind(ipEndPoint);
mainSocket.Listen(MAX_CONNECTIONS);
mainSocket.BeginAccept(new AsyncCallback(serverEndAccept), mainSocket);
OnNetworkEvents eventArgs =
new OnNetworkEvents(true, "Listening for Connection");
OnUpdateNetworkStatusMessage(this, eventArgs);
}
catch (SocketException e)
{
// add code here
}
catch (ObjectDisposedException e)
{
// add code here
}
How do I test the code's SocketException given the server is listening successfully all of the time?
Do not test against the live network. Mock the socket and test against a mock that throws a SocketException.
you could add something like this for testing:
#if (UNITTEST)
throw new SocketException();
#endif
Then in your unit test compile just define that variable.
Otherwise do something to force an exception. Like have an invalid config setting that won't let it connect for use with your unit test code.
Unplug your network cable or shut off your wireless (assuming you're testing against a remote server).
Manually throw a SocketException from inside your try block.
Like
throw new SocketException("Testing");

Categories