简体   繁体   中英

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#.

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#:

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:

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

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#.

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 . As you can see here , 25566 is actually 63DE in hex.

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? I suggest using Craft.Net , instead of trying to roll your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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