简体   繁体   English

将PHP转换为C#

[英]Conversion of PHP to C#

I've been working on this for about an hour now and I can't manage to get the uint16 packed in the right format in C#. 我已经为此工作了大约一个小时,而且我无法以C#格式正确打包uint16。

PHP: PHP:

$data = "\x00"; //packet id
$data .= "\x04"; //protocol version
$data .= pack('c', strlen($server_address)) . $server_address; //server address
$data .= pack('n', $server_port); //server port
$data .= "\x01"; //next state

$data = pack('c', strlen($data)) . $data;

return $data;

C#: C#:

string packet_id = "\x00";
string protocol_version = "\x04";
string server_address = new string(new char[] { Convert.ToChar(this.server_address.Length) }) + this.server_address;
//byte[] port_array = BitConverter.GetBytes((ushort)this.server_port);
//Array.Reverse(port_array);
string server_port = Convert.ToString((ushort)this.server_port);
string next_state = "\x01";

string final = packet_id + protocol_version + server_address + server_port + next_state;
final = new string(new char[] { Convert.ToChar(final.Length) }) + final;

The results as hex are as follows: PHP: 结果为十六进制,如下所示:PHP:

12 00 04 0C 31 39 38 2E 32 37 2E 38 33 2E 33 35 63 DE 01

C#: C#:

15 00 04 0C 31 39 38 2E 32 37 2E 38 33 2E 33 35 32 35 35 36 36 01

As you can see the server port (25566) is 63 DE in PHP but 32 35 35 36 36 in C#. 如您所见,服务器端口(25566)在PHP中为63 DE,而在C#中为32 35 35 36 36。

The simplest way to do this is with a byte array and bitwise operations: 最简单的方法是使用字节数组和按位操作:

byte[] data = new byte[] {
    (byte) (((ushort) this.server_port) >> 8),
    (byte) ((ushort) this.server_port)
};
string server_port = (string) data;

It's also worth noting that your PHP output actually depicts 25565 , not 25566 . 还值得注意的是,您的PHP输出实际上描述的是25565而不是 25566 As you can see here , 25566 is actually 63DE in hex. 正如你可以看到这里25566实际上是63DE十六进制。

I suggest you to use this code for conversion of port: 我建议您使用以下代码转换端口:

this.server_port.ToString("X")

It will convert number you gave to hexadecimal representation in string 它将您输入的数字转换为字符串中的十六进制表示形式

Are you trying to ping a server? 您是否要ping服务器? I suggest using Craft.Net , instead of trying to roll your own. 我建议使用Craft.Net ,而不要尝试自己动手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM