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
Solved

NetworkStream.Write - Malformed Packet

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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

Join Greg Farro and Ethan Banks from Packet Pushers (http://packetpushers.net/podcast/podcasts/pq-show-93-smart-network-monitoring-paessler-sponsored/) and Greg Ross from Paessler (https://www.paessler.com/prtg) for a discussion about smart network …
When you try to share a printer , you may receive one of the following error messages. Error message when you use the Add Printer Wizard to share a printer: Windows could not share your printer. Operation could not be completed (Error 0x000006…
After creating this article (http://www.experts-exchange.com/articles/23699/Setup-Mikrotik-routers-with-OSPF.html), I decided to make a video (no audio) to show you how to configure the routers and run some trace routes and pings between the 7 sites…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

789 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