UdpClient Constructor Throwing SocketException - c#

I'm experiencing an exception upon construction of a UdpClient object, specifying the IPv4 family. This is only occuring on one Windows 7 64-bit machine, other machines with the same OS are working fine.
The precise exception is:
System.Net.Sockets.SocketException (0x80004005): An invalid argument was supplied
at System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
at System.Net.Sockets.UdpClient.createClientSocket()
SocketException.ErrorCode is WSAEINVAL 10022, InvalidArgument.
The code that's throwing this exception:
this.udpClient = new UdpClient(AddressFamily.InterNetwork);
Can anyone explain what this exception is telling me? How can IPv4 be an invalid argument for a new UDP client?
UPDATE: This is only occurring when running the application from a network drive. Running it locally does not cause this exception.

The docs advise you to check SocketException::ErrorCode in this instance. What's the value of that? Should be instructive. The Family param is fine, I would think, or you would get ArgumentException.
If you receive a SocketException, use
SocketException::ErrorCode to obtain
the specific error code. Once you have
obtained this code, you can refer to
the Windows Sockets version 2 API
error code documentation in MSDN for a
detailed description of the error.

0x80004005 is an access denied, you do not have rights to create a socket, maybe your firewall?
Or your socket is in use, have you killed the program without terminating the socket?

Related

Get a StreamSocket's Connection Status (UWP)

I'm using a StreamSocket in a Windows Universal app to make a TCP/IP connection to a text based game (the socket is left open for an extended period of time). I have it connecting and returning data fine. Most socket implementations I've used in the past have a property or function (or a way to poll the socket) and get the status (whether it's open, closed, broken, pending, etc.).
I haven't been able to find a way to do this with the StreamSocket.
My question is, How do I query the status of the StreamSocket connection to see if it's dropped (without waiting until I send something down the pipe for it to error out)?
E.g., something so I could do something like:
if (this.Socket.Status != Status.Connected)...
if (this.Socket.Status != Status.Connected)
The code you wrote was quite elegant , however, as far as I know there is no such api provided by uwp.
The Windows.Networking.Sockets namespace has convenient helper methods and enumerations for handling errors when using sockets and WebSockets. This can be useful for handling specific network exceptions differently in your app.
An error encountered on DatagramSocket, StreamSocket, or StreamSocketListener operation is returned as an HRESULT value. The SocketError.GetStatus method is used to convert a network error from a socket operation to a SocketErrorStatus enumeration value. Most of the SocketErrorStatus enumeration values correspond to an error returned by the native Windows sockets operation. An app can filter on specific SocketErrorStatus enumeration values to modify app behavior depending on the cause of the exception.
For parameter validation errors, an app can also use the HRESULT from the exception to learn more detailed information on the error that caused the exception. Possible HRESULT values are listed in the Winerror.h header file. For most parameter validation errors, the HRESULT returned is E_INVALIDARG
.

Transport errors

I'm working on a crawler and my attempt at fixing an issue with this exception:
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
was to implement a retry pattern after using wireshark and looking at network logs I concluded that these errors are most likely transient.
However these exceptions are really bugging me now and I would really like to get to the bottom of why I am getting these errors. Can anyone suggest a good strategy to adopt and tools I can use or reasons you can think of why the connection is being forcibly closed?
Thanks
I see two questions here:
Why is the Exception being thrown?
Why is the connection being forcibly closed?
Why is the Exception being thrown?
This is a problem with the transport implementation you have chosen to consume. Apparently, microsoft decided to communicate the error by wrapping it up in an exception and throw it up the stack. The corresponding source code can be found here: http://referencesource.microsoft.com/#System/net/System/Net/Sockets/NetworkStream.cs,766
In the source code, you can also see that the InnerException is set and contains a localization independent representation of the errorCode.
The bottom line is that this exception being thrown does not mean anything exceptional happened, it can happen just because the connection was dropped.
Which brings us to the next question:
Why is the connection being forcibly closed?
Just as the exceptions message hints, the reason could well be the remote host. Therefore, looking at the remote hosts implementation could be required to get to the bottom of this.
I suspect though, that just judging by the exception, you cannot rule out the reason to be somewhere in between the hosts (sharks have shown an appetite for fiber cables).
I suggest the following experiment:
Set up the two hosts residing on different machines and let them connect through a cable.
While the connection is established, unplug the cable.
This could not disproof but at least proof the possibility.
However, "working on a crawler" suggests that you might encounter a variety of different hosts and it is to be expected that some of them turn taciturn sometimes for whatever reason you would care to imagine.
EDIT:
I remember catching this exception when using TCP over IP when the remote host sent a packet with the RST Flag set. The value of the RST Flag is displayed in Wireshark.
networkstream
My 50 cents: This is the normal behaviour when using networkstreams for reading data from a socket. It is not a user error, the exception thrown just causes the data processing in the reading thread to be interrupted. Just wrap it up with a try/catch-handler accordingly.
You could try to use the DebuggerNonUserCode attribute (https://msdn.microsoft.com/de-de/library/system.diagnostics.debuggernonusercodeattribute%28v=vs.110%29.aspx) to suppress debugger alerts when an exception is triggered. Be aware that this may also "hide" other exceptions...

Issues connecting ibm mq client to a lower version

I am using 7x (7.5 mq client amqmdnet.dll) via .net and using MQPutMessageOptions and MQGetMessageOptions, this code works fine with mq 7.5 ibm client, however
IBM link
says 7x mq client will be backward compatible with 6x, when i try to connect, i get this error (am in a windows 7 64-bit OS).
System.TypeInitializationException: The type initializer for 'IBM.WMQ.MQQueueManager' threw an exception. ---> System.TypeInitializationException: The type initializer for 'IBM.WMQ.CommonServices' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at IBM.WMQ.CommonServices..cctor()
--- End of inner exception stack trace ---
at IBM.WMQ.CommonServices.TraceEnabled()
at IBM.WMQ.MQBase..ctor()
at IBM.WMQ.Nmqi.NmqiEnvironment..ctor(NmqiPropertyHandler nmqiPropertyHandler)
at IBM.WMQ.Nmqi.NmqiFactory.GetInstance(NmqiPropertyHandler properties)
at IBM.WMQ.MQQueueManager..cctor()
The line that throws the above error is :
MQQueueManager mqQMgr = new MQQueueManager("My queue manager" , "my channel name" ,"my connection name");
PS: the above line with the same params work fine in 7.5 mq client , but fails when a 6x (for ex: 6.0.2.5 mq client is installed, i have done 'typical' installation (full installation of 6x mq client).
Any idea how to make it work with 6.0.2.5?
Yes, that link is correct. What the link is saying if you have MQ v7.5 client installed, you will be able to work with MQ v6.0 queue manager running on a remote machine. But what you are trying appears to be different. You appear to have compiled the application with MQ v7.5 client but trying to run it on MQ v6.0.x client. This will not work.

Wince Socket exception on asynchronous HTTP request

I am writing a WinCE app in C# that makes an HTTP POST to an APACHE server residing on my network. Because of some network issues (I am guessing), I get the following exception in the managed code
System.Net.Sockets.SocketException occurred
Message="A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"
ErrorCode=10060
NativeErrorCode=10060
StackTrace:
at System.Net.Sockets.Socket.ConnectNoCheck(EndPoint remoteEP)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at System.Net.Connection.doConnect(IPEndPoint ep)
at System.Net.Connection.connect(Object ignored)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
This exception isn't always thrown, but when it is thrown, my app fails to connect to the server AT ALL. Repeated connection attempts don't help in reconnecting either. The only thing that helps is closing and re-deploying the app.
I can't catch the exception because its inside of managed code. Is there any way to circumvent this and close all socket connections to my server and re-initialize them? Is there something I am doing wrong?
The exception message looks a bit misleading ("connection attempt failed because the connected party") but I think it means your hardware is communicating with the server, but the server is not accepting the connection on the TCP level.
A problem I could think of is "hanging" connections, causing the server to reach the maximum number of concurrent connections and to stop accepting new ones.
Although it's just a guess, you might want to check the apache log if you can to see if you can find out if the server reports anything, and perhaps try restarting apache as soon as the problem occurs again. If that helps, you still need to find the cause of course.

asp.net NetworkInformationException on sending mail - what can be the reason?

SmtpClient smtp = new SmtpClient(smtpServer);
smtp.Send(msgMail);
On second line sometimes this exception is thrown:
System.Net.NetworkInformation.NetworkInformationException:
with Message: "A non-blocking socket operation could not be completed immediately"
What does that mean? What can be the reason?
Mail sending in general is working most times.
It's a IIS7 Windows 2008 Server machine.
Thank you.
Edit:
I found something here:
http://www.thevbzone.com/modWINSOCK.bas
Public Const WSAEWOULDBLOCK = (WSABASEERR + 35) ' A non-blocking socket operation could not be completed immediately
MSDN says about this error (http://msdn.microsoft.com/en-us/library/ms740668%28VS.85%29.aspx):
Resource temporarily unavailable.
This error is returned from operations on nonblocking sockets that
cannot be completed immediately,...
So, what does that mean actually? Should I just ignore the error, resend the mail...? thanks.
First of all you should check ErrorCode property of NetworkInformationException and then find this error code in this ms article. It gives to you more information about exception.

Categories