草庐IT

c# - 自定义 TCP header /从 wireshark 数据包复制 TCP header

coder 2023-09-19 原文

我正在尝试为这个用于 LED 标志的“异步”嵌入式卡编写网络接口(interface)。现有软件叫“PlutoManager”,但它是中国制造的,我们的老客户很难使用。

该软件通过以太网电缆与嵌入式卡(称为 PSD100)交互来执行许多操作。

我查看了一些文档,文档指出该卡通过标准 TCP/IP 协议(protocol)进行通信。 (或者类似TCP/IP的东西,不太确定)

我从我拿到的中文文档中翻译了一些东西,这就是我找到的关于卡协议(protocol)的内容:

(我对 TCP/IP 不太了解,所以这个翻译可能很粗糙,请记住这些词可能是错误的词,这可能是我的问题的很大一部分。)

因此对于与卡的每次通信(发送文件、握手、改变 LED 标志的亮度等)都必须发生两件事:

  • 一条消息被发送到卡片(请求数据包)
  • 收到来自卡片的回复(回复包)

请求包结构如下:(来自中文,我的翻译很烂)

> 1. Header:  1 byte (16 bits) with a hex value of "0x02" 

 >2. Card Address(??):  2 bytes (32 bits) 
 >3. Packet Type:  2 bytes (32 bits)
 >4. data: indeterminate length
 >5. CRC Check: 2 bytes (32 bits) 
 >6. End of Text Character:  1 byte (16 bits) (value: "0x03" [I guess that's equal to ^c ?]

这看起来像正常的 TCP/IP 结构吗?在我对自定义数据包着迷之前?

我想我可以使用 Wireshark 嗅探 PlutoManager 进行握手时发送的数据包。我还在 C# 中编写了一些代码,试图与设备的端口建立连接。这是两个并排的。请注意,这只是转储的 TCP 数据包部分,wireshark 输出的 TCP 部分是唯一不同的部分。

TCP SEGMENT CAPTURED FROM WIRESHARK HEX + ASCII DUMP (FROM MY C# CODE)
HEX
0000   d0 6b 7a 43 5e a3 79 62 67 78 dc bf 50 10 80 51        ASCII:    .kzC^.ybgx..P..Q
0010   46 60 00 00                                                F`..

TCP SEGMENT CAPTURED FROM WIRESHARK HEX + ASCII DUMP (PLUTOMANAGER CODE)

HEX
0000   7a 42 d0 6a 34 17 04 36 5e a3 0b 1d 50 10 01 00     ASCII:  zB.j4..6^...P...
0010   82 50 00 00       

我想,“嘿,我可以使用 Send() 命令向卡发送自定义负载并复制 PlutoManager 代码正在执行的操作!”

我不知道这个中文软件是否使用一些特殊的 TCP 有效负载向标志发送消息,或者它是否使用标准协议(protocol)。而且我不知道如何发现差异。我曾尝试使用 Pcap.net 发送自定义有效负载,但在我继续深陷困境之前,这似乎是必要的吗? 第二个 Wireshark 输出是 TCP/IP 协议(protocol)中常见的东西吗?是否可以按顺序发送字符串“zB/^T3mPP”(这是该握手的十六进制转储输出)使握手发生?

这就是我目前构建程序的方式(基本上是 str:

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

// State object for receiving data from remote device.
public class StateObject
{
    // Client socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 256;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    // The port number for the remote device.
    private const int port = 31298;

    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone =
        new ManualResetEvent(false);
    private static ManualResetEvent sendDone =
        new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =
        new ManualResetEvent(false);

    // The response from the remote device.
    private static String response = String.Empty;

    private static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the 
            // remote device is "host.contoso.com".
            //IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
            IPAddress ipAddress = IPAddress.Parse("192.168.0.59");  //ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            // Send test data to the remote device.
            Send(client, "This is a test<EOF>");
            sendDone.WaitOne();

            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Response received : {0}", response);

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete the connection.
            client.EndConnect(ar);

            Console.WriteLine("Socket connected to {0}",
                client.RemoteEndPoint.ToString());

            // Signal that the connection has been made.
            connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void Receive(Socket client)
    {
        try
        {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                // Get the rest of the data.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            else
            {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void Send(Socket client, String data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        client.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), client);
    }

    private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);

            // Signal that all bytes have been sent.
            sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public static int Main(String[] args)
    {
        StartClient();
        return 0;
    }
}

Main() 运行命令 StartClient() 尝试连接,但最终输出错误消息:

System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it 192.168.0.59:31298
    at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
    at AsynchronousClient.ConnectCallback(IAsyncResult ar) in C:\Users\xxxxx\Desktop\SocketListenerTest\SocketListenerTest\SocketListenerTest\Program.cs:line 87

第 87 行是: client.EndConnect(ar);

这让我觉得我正在连接到正确的 IP 和正确的端口,但是 .NET 中内置的协议(protocol)和这个嵌入式设备使用的协议(protocol)是不同的。

我可以访问包含该设备某些规范的中文文档(我会发布它,但它处于保密协议(protocol)之下)。如果我遗漏了什么,或者如果您需要文档中的更多信息,我会尽我所能发布。我尽量提供最相关的信息,但这对我来说很陌生。

我想我可以将问题简化为“如何修改 Sockets.Connect() 方法以使用自定义 TCP 协议(protocol)?” 但我认为最好提供更多信息对我想要完成的事情的总体概述,因为这可能不是我需要做的。

感谢您花时间查看此问题。如果您有任何建议,甚至是指点我去图书馆或书籍或某种阅读 Material ,我很乐意听取。谢谢。

最佳答案

这个答案可能来得有点晚,但是您得到的 SocketException 指的是端点拒绝整个连接而不仅仅是自定义部分(在有效负载中)这一事实。

可能是上述 PlutoManager 使用特定的源端口进行通信,而嵌入式设备的防火墙拒绝来自所有其他源端口的连接。您可以使用 Wireshark 检查源端口并为您的 Socket 客户端定义一个源端口,如下所示:

Socket client = new Socket(AddressFamily.InterNetwork,
                           SocketType.Stream,
                           ProtocolType.Tcp);
client.Bind(new IPEndPoint(IPAddress.Any, 32000)); //The port number that PlutoManager uses

希望对您有所帮助。

关于c# - 自定义 TCP header /从 wireshark 数据包复制 TCP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39088798/

有关c# - 自定义 TCP header /从 wireshark 数据包复制 TCP header的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  4. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  5. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  6. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  7. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  8. ruby - 如何在 Grape 中定义哈希数组? - 2

    我使用Ember作为我的前端和GrapeAPI来为我的API提供服务。前端发送类似:{"service"=>{"name"=>"Name","duration"=>"30","user"=>nil,"organization"=>"org","category"=>nil,"description"=>"description","disabled"=>true,"color"=>nil,"availabilities"=>[{"day"=>"Saturday","enabled"=>false,"timeSlots"=>[{"startAt"=>"09:00AM","endAt"=>

  9. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  10. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

随机推荐