Solved

NetworkStream.Write - Malformed Packet

Posted on 2011-09-29
5
1,230 Views
Last Modified: 2012-05-12
I am attempting to send a very simple packet of data over a TCP connection.  My server never received the packet, so I connected Wireshark to see what was happening.  Wireshark is reporting it as a "Malformed Packet"  (packet 1625 of attached capture).  I do not understand what is wrong with the data I am sending (or how I'm sending it).

 
tcpClient = new TcpClient(ipAddress, PORTNUMBER);
netStream = tcpClient.GetStream();

BinaryWriter packet = new BinaryWriter(new MemoryStream(sendBuffer));

packet.Write((uint)BodyType.cmd_GETCALIBPOS);
packet.Write((uint)8);

packet.Write((uint)data1);
packet.Write((uint)data2);

netStream.Write(sendBuffer, 0, 16);

Open in new window


 Packet 1625
0
Comment
Question by:WCDeveloper
  • 3
  • 2
5 Comments
 
LVL 15

Assisted Solution

by:x77
x77 earned 500 total points
ID: 36890000
You are using --- netStream.Write(sendBuffer, 0, 16);   ???

- When you create a memory stream, it has own private buffer.     sample:  new memorystream(1024)

- When yuo create the stream using    new memorystream(mybuffer)  :

            ms = new memorystream(mybuffer.lentgth);
            ms.write(mybuffer,0,mybuffer.length)

Memorystream   always has own buffer.

Use memorystream.getbuffer()  to get  memorystream buffer and use it.
Note that each time you write over a memory stream, it can realocate a new buffer.
The    memorystream.getbuffer()    is valid only  until  new data is added to memorystream.

----------------------------------------

I don´t understand the use of netstream at this sample
you can write data using  Socket.Send:

       MemoryStream ms = (memorystream)(packet.basestream);
       tcpClient.Send(  ms.getbuffer, 0, (int)ms.length);
           
0
 

Author Comment

by:WCDeveloper
ID: 36891187
I have verified in the debugger that my "sendBuffer" does in fact have the data populated.

The reason I'm using NetworkStream is because the TcpClient class does not expose the "send" method.  It only allows access to the NetworkStream.  Read/Writing must be done on the stream.
0
 
LVL 15

Accepted Solution

by:
x77 earned 500 total points
ID: 36891744
I has done some work with NetworkStream on input side, but never try it on Output side.
I use bufered input, but write using Socket.Send method.

 
clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        clientSocket.ReceiveTimeout = 5000
        clientSocket.SendTimeout = 5000
        clientSocket.Connect(Dns.GetHostEntry(remoteHost).AddressList(0), remotePort)
        ClientStream = New StreamReader(New NetworkStream(clientSocket))
....

    Public Sub Cmd(ByVal command As String)
        Dim commandBytes() As Byte = ASCII.GetBytes(command)
        clientSocket.Send(commandBytes, commandBytes.Length, 0)
    End Sub

     Private Function ClientRead(ByVal Query As String) As String
        Lines.Clear()
        Dim s As String
        Do
           s = ClientStream.ReadLine
           Lines.Add(s)
           If s IsNot Nothing AndAlso s.StartsWith("5") Then
              Dim msg = String.Join(ControlChars.CrLf, Lines.ToArray)
              Close()
              Throw (New Exception(msg))
           End If
        Loop Until s.StartsWith(Query)
        PendingResponse = Nothing
        Lines.Clear()
        Return s
     End Function

Open in new window


It Works.
I use the Ftp Protocol, then I need detect  End Of Line (StreamReader.ReadLine).
Using TcpClient.Send, I can control how many information I put on each message I send.
Using NetworkStream, you don´t know when network stream Flush.
0
 
LVL 15

Expert Comment

by:x77
ID: 36891911
You can examine NetworkStream with Reflector:


Public Overrides Sub Write(ByVal buffer As Byte(), ByVal offset As Integer, ByVal size As Integer)
     ....
     streamSocket.Send(buffer, offset, size, SocketFlags.None)


Then NetworkStream on Output is full transparent from StreamSocket.
Public Overrides Sub Write(ByVal buffer As Byte(), ByVal offset As Integer, ByVal size As Integer)
    If Me.m_CleanedUp Then
        Throw New ObjectDisposedException(MyBase.GetType.FullName)
    End If
    If (buffer Is Nothing) Then
        Throw New ArgumentNullException("buffer")
    End If
    If ((offset < 0) OrElse (offset > buffer.Length)) Then
        Throw New ArgumentOutOfRangeException("offset")
    End If
    If ((size < 0) OrElse (size > (buffer.Length - offset))) Then
        Throw New ArgumentOutOfRangeException("size")
    End If
    If Not Me.CanWrite Then
        Throw New InvalidOperationException(SR.GetString("net_readonlystream"))
    End If
    Dim streamSocket As Socket = Me.m_StreamSocket
    If (streamSocket Is Nothing) Then
        Throw New IOException(SR.GetString("net_io_writefailure", New Object() { SR.GetString("net_io_connectionclosed") }))
    End If
    Try 
        streamSocket.Send(buffer, offset, size, SocketFlags.None)
    Catch exception As Exception
        If ((TypeOf exception Is ThreadAbortException OrElse TypeOf exception Is StackOverflowException) OrElse TypeOf exception Is OutOfMemoryException) Then
            Throw
        End If
        Throw New IOException(SR.GetString("net_io_writefailure", New Object() { exception.Message }), exception)
    Catch obj1 As Object
        Throw New IOException(SR.GetString("net_io_writefailure", New Object() { String.Empty }), New Exception(SR.GetString("net_nonClsCompliantException")))
    End Try
End Sub

Open in new window

0
 

Author Closing Comment

by:WCDeveloper
ID: 36893842
Changed my implementation to use the Socket class instead of the TcpClient class.  Now it's working fine.

Thanks!
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, I am going to show you how to simulate a multi-site Lab environment on a single Hyper-V host. I use this method successfully in my own lab to simulate three fully routed global AD Sites on a Windows 10 Hyper-V host.
This article will inform Clients about common and important expectations from the freelancers (Experts) who are looking at your Gig.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question