Solved

NetworkStream.Write - Malformed Packet

Posted on 2011-09-29
5
1,217 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
If you're not part of the solution, you're part of the problem.   Tips on how to secure IoT devices, even the dumbest ones, so they can't be used as part of a DDoS botnet.  Use PRTG Network Monitor as one of the building blocks, to detect unusual…
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…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

743 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now