Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

NetworkStream.Write - Malformed Packet

Posted on 2011-09-29
5
Medium Priority
?
1,285 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 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

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

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

If you’re involved with your company’s wide area network (WAN), you’ve probably heard about SD-WANs. They’re the “boy wonder” of networking, ostensibly allowing companies to replace expensive MPLS lines with low-cost Internet access. But, are they …
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
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 …
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

578 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