Error 10042 - A bad option or level was specified in a getsockopt or setsockopt

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Goyem
    New Member
    • May 2010
    • 6

    #1

    Error 10042 - A bad option or level was specified in a getsockopt or setsockopt

    I’m trying to build an application in VB.NET that read GPRS communication protocols, between a GPS Tracker and Server, but when my socket tries to begin receiving the data that came from the tracker I get the error 10042.

    Anyone knows what can make this to happen??? And how to fix it???

    (I also wrote a client app to prove it with my server side app and it works good)

    I'm posting the entery code so you can see it well.
    Code:
    Imports System
    Imports System.Net
    Imports System.Net.Sockets
    Imports System.Text
    Imports System.Threading
    Imports Microsoft.VisualBasic
    
    ' State object for reading client data asynchronously
    
    Public Class StateObject
        ' Client  socket.
        Public workSocket As Socket = Nothing
        ' Size of receive buffer.
        Public Const BufferSize As Long = 1078624
        ' Receive buffer.
        Public buffer(BufferSize) As Byte
        ' Received data string.
        Public sb As New StringBuilder
    End Class 'StateObject
    
    
    Public Class AsynchronousSocketListener
        ' Thread signal.
        Public Shared allDone As New ManualResetEvent(False)
    
        ' This server waits for a connection and then uses  asychronous operations to
        ' accept the connection, get data from the connected client, 
        ' echo that data back to the connected client.
        ' It then disconnects from the client and waits for another client. 
        Public Shared Sub Main()
            ' Data buffer for incoming data.
            Dim bytes() As Byte = New [Byte](1023) {}
    
            ' Establish the local endpoint for the socket.
            Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
            Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
            Dim localEndPoint As New IPEndPoint(ipAddress, 8000)
    
            ' Create a TCP/IP socket.
            Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    
            ' Bind the socket to the local endpoint and listen for incoming connections.
            listener.Bind(localEndPoint)
            listener.Listen(100)
    
            While True
                ' Set the event to nonsignaled state.
                allDone.Reset()
    
                ' Start an asynchronous socket to listen for connections.
                Console.WriteLine("Waiting for a connection...")
                listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)
    
                ' Wait until a connection is made and processed before continuing.
                allDone.WaitOne()
            End While
        End Sub 'Main
    
    
        Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
            ' Get the socket that handles the client request.
            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
    
            Dim handler As Socket = listener.EndAccept(ar)
    
            ' Create the state object for the async receive.
            Dim state As New StateObject
            state.workSocket = handler
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
            'handler.BeginConnect 
        End Sub 'AcceptCallback
    
    
        Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
            Dim content As String = String.Empty
    
            ' Retrieve the state object and the handler socket
            ' from the asynchronous state object.
            Dim state As StateObject = CType(ar.AsyncState, StateObject)
            Dim handler As Socket = state.workSocket
    
            ' Read data from the client socket. 
            Dim bytesRead As Integer = handler.EndReceive(ar)
    
            If bytesRead > 0 Then
                ' There  might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))
    
                ' Check for end-of-file tag. If it is not there, read 
                ' more data.
                content = state.sb.ToString()
                If content.IndexOf("\r\n") > -1 Then
                    ' All the data has been read from the 
                    ' client. Display it on the console.
                    Console.WriteLine("Read {0} bytes from socket. " + vbLf + " Data : {1}", content.Length, content)
                    ' Echo the data back to the client.
                    Send(handler, content)
                Else
                    ' Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
                End If
            End If
        End Sub 'ReadCallback
    
        Private Shared Sub Send(ByVal handler As Socket, ByVal data As String)
            ' Convert the string data to byte data using ASCII encoding.
            Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
    
            ' Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), handler)
        End Sub 'Send
    
    
        Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
            ' Retrieve the socket from the state object.
            Dim handler As Socket = CType(ar.AsyncState, Socket)
    
            ' Complete sending the data to the remote device.
            Dim bytesSent As Integer = handler.EndSend(ar)
            Console.WriteLine("Sent {0} bytes to client.", bytesSent)
    
            handler.Shutdown(SocketShutdown.Both)
            handler.Close()
            ' Signal the main thread to continue.
            allDone.Set()
        End Sub 'SendCallback
    End Class 'AsynchronousSocketListener
    Last edited by Niheel; May 27 '10, 06:41 PM. Reason: merged code with question
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Could you post the socket related calls that your code makes.

    Particularly any calls to getsockopt or setsockopt if the code calls them directly.

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      Ok, this is an interesting problem.

      I don't see anything that immediately jumps out at me as wrong in your code.

      Btw, Banfa the getsockopt and setsockopt are not part of the OP's code: Article on some old school stuff concerning Winsock.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        No that is true but his error message suggests they are getting called somewhere and I imagine that underneath it all the .NET library still calls out to WinSock2

        Is SocketType.Stre am correct, on MSDN the examples use SocketType::Str eam

        FYI Goyem I am more of a networking expert than a .NET expert but luckily we have Frinny in here for the .NET stuff.

        Comment

        • Goyem
          New Member
          • May 2010
          • 6

          #5
          Banfa, I'm using a SocketType.Stre am because i'm using a two way tcp connection. I don't know if that is correct but in theory it is correct.

          I talked with the people that sold me the tracker, and they told me that maybe is because of the protocol that the tracker use. That only make me anger. lol.

          I don't know what else 2 do, any ideas on how to manage this protocols? If you need I can upload de gprs comunication protocol between gps tracker and server...
          Last edited by Niheel; May 27 '10, 06:42 PM. Reason: punctuation and removed unnecessary thank yous

          Comment

          • Banfa
            Recognized Expert Expert
            • Feb 2006
            • 9067

            #6
            No socket type stream is the correct one to use I was questioning the syntax

            SocketType.Stream

            as opposed to

            SocketType::Stream

            Can you say at what point in the code the error is reported and if any other information is given with the error report?

            Comment

            • Frinavale
              Recognized Expert Expert
              • Oct 2006
              • 9749

              #7
              The syntax looks fine to me :)
              This is VB.NET not C#/C++
              I seriously can't see anything wrong with the code (it's not the way I would have implemented it but it looks correct). Maybe seeing the sepcs for the device might help

              Comment

              • Banfa
                Recognized Expert Expert
                • Feb 2006
                • 9067

                #8
                Erm you have you thread title wrong

                A bad option or level was specified in a getsockopt or setsockopt is error 10042

                Error 10024 is

                Originally posted by MSDN
                //
                // MessageId: WSAEMFILE
                //
                // MessageText:
                //
                // Too many open sockets.
                //
                #define WSAEMFILE 10024L
                So which error do you actually have?

                Comment

                • Goyem
                  New Member
                  • May 2010
                  • 6

                  #9
                  the error is 10042, sorry about that.
                  The error is generatered in code line 70.

                  Comment

                  • Banfa
                    Recognized Expert Expert
                    • Feb 2006
                    • 9067

                    #10
                    Well I can tell you what the problem is, apparently the socket has not actually finished connecting properly by the time you call BeginReceive. It appears this is a bug in the .NET framework that existed in 3.5 as recently as August 2009.

                    Because the connection is not properly established when you call BeginReceive an exception is raise, in your case 10042 but others can occur apparently.

                    I can not locate a fix for this particular problem, there is a kludge which is to put a 5 - 10 second thread delay just before the BeginReceive call.

                    I would recommend with something like sockets that you consider putting some exception handling into your code (does VB.net do exception handling?).

                    You can get direct access to the source of all this information by googling "10042 BeginReceive"

                    Comment

                    • Frinavale
                      Recognized Expert Expert
                      • Oct 2006
                      • 9749

                      #11
                      Yup VB.NET has Try Catch blocks :)
                      Just no curly braces

                      Comment

                      • Plater
                        Recognized Expert Expert
                        • Apr 2007
                        • 7872

                        #12
                        I have actually hit the "too many open sockets" issue when performing a stress test on some hardware. When I did a "NETSTAT -a" at a command prompt, I had a lot of scrolling, because I had filled them up.
                        Are you doing an excessive amount of opening/closing of sockets?

                        Comment

                        • Goyem
                          New Member
                          • May 2010
                          • 6

                          #13
                          Plater, I make a mistake in the title, error code is 10042.

                          Banfa, I did a research in what you suggest and added a Thread.Sleep before the BeginAccept and i got the same response.

                          Frinavale, the device that I'm using is a TK310 GPS Tracker, using GPRS comunication protocols between the tracker and server. Maybe the problem is on how to used the protocols, but the truth is that I got no idea on how to deal with it, or if i'm doing the communication correctly

                          Comment

                          • Banfa
                            Recognized Expert Expert
                            • Feb 2006
                            • 9067

                            #14
                            It might be using GPRS but as far as the server is concerned it should be just another tcp connection. All the GPRS stuff should be being handled by your network operator.

                            P.S. Correcting number in the title

                            Comment

                            • Goyem
                              New Member
                              • May 2010
                              • 6

                              #15
                              I think I pass through this problem, but know I have another issue.
                              Know I'm getting error code 10054:an existing connection was forcibly closed by the remote host.

                              P.S. googling it

                              Comment

                              Working...