Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

NetworkStream.Write - Malformed Packet

Posted on 2011-09-29
5
Medium Priority
?
1,266 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 15

Assisted Solution

by:x77
x77 earned 2000 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 2000 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

I had an issue with InstallShield not being able to use Computer Browser service on Windows Server 2012. Here is the solution I found.
This month, Experts Exchange’s free Course of the Month is focused on CompTIA IT Fundamentals.
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…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …

688 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