Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

c# - How to get a string from a bytes array?

I'm creating my own DNS server and host blocker, I want to get host from DNS request message byte[]

dns message hex dump:

e07901000001000000000000057961686f6f03636f6d0000010001
.y...........yahoo.com.....

code:

using System;
using System.Text;

public class Program
{
    public static void Main()
    {
        string b64 = "4HkBAAABAAAAAAAABXlhaG9vA2NvbQAAAQAB";
        int pad = b64.Length % 4;
        if (pad > 0 )
        {
            b64 += new string('=', 4 - pad);
        }
        byte[] decoded = Convert.FromBase64String(b64);
        int start = 13;
        int end = start;
        while(decoded[end] != 0){
            end++;
        }
        
        int hostLength = end-start;
        byte[] byteHost = new byte[hostLength];
        Array.Copy(decoded, start, byteHost, 0, hostLength);
        string host = Encoding.Default.GetString(byteHost);
        Console.WriteLine(host); // yahoo?com
    }
}

The questions:

  1. is my method above to get host name right/efficient/fastest ?
  2. why I get weird character replacing the dot yahoo?com ?

change to Encoding.ASCII or Encoding.UTF8 has no effect

question from:https://stackoverflow.com/questions/65933992/how-to-get-a-string-from-a-bytes-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. There's no need for the second array; Encoding.GetString allows you to pass in an offset and count, so: GetString(decoded, start, hostLength)
  2. Never use Encoding.Default; that is badly named - it should be called Encoding.Wrong :) Find out what encoding the data is in (probably UTF-8 or ASCII), and use that
  3. You should be able to use IndexOf to find the terminating ''; also consider what your code should do if it doesn't find one

As for the unusual character: the data contains an 03 byte where you would expect the .; check the DNS protocol specification to see if this is expected. 03 is ETX (end of text). Beyond that: I don't know.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...