Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top