简体   繁体   中英

C# - Server-side password protection

I am writing two console applications, a client and a server. I'm a little stuck at two things, which seemed rather easy at first..

#1: I want to write a function for the following piece of code, that converts bits to a string, but I cant just figure it out. The server always crashes when I use it. My function is a little bit different than this one, but that's because my current code has to include the connection information, and I think there's a better way to do it:

        byte[] b = new byte[100];
        int k = s.Receive(b);

            string packet = null;
        for (int i = 0; i < k; i++)
        {
            Console.Write(Convert.ToChar(b[i]));
            packet = packet + Convert.ToChar(b[i]);
        }

I guess the function is not the problem, but how I use it is. Any help would be very much apreciated.

Edit: I am calling and using it like this:

    byte[] b = new byte[100];
    string response = BitConvert(b);

    if (response == "Hi there")

#2 I want the client to álways send a packet just once, with a password. And if that password doesn't match the password mentioned as a string in the server, it should close the connection with the client.

I know how to send the packet just once, but I don't know how to check the packet in the server just once for each client.

Or in other words, at the moment the server has no way of knowing if the client has already been authenticated. So I guess the client needs to have some sort of socket ID, and the server needs a table with the ID, and a boolean to see if it's autenticated or not.

The first part, getting the bytes into a string ... how about:

byte b[] = new byte[100];
int k = s.Receive(b, b.Length, 0);

string packet = Encoding.ASCII.getString(b, 0, k);

Part 2 ... not sure off the top of my head.

I'm with Rob above on part 1 and as for part 2... Assuming you're using a TCP connection the System.Net.Sockets class should handle your needs.

If you use either AcceptSocket or AcceptTcpClient to pull a connection from the incoming connection request queue you'll get a socket or tcpclient that is unique to that connection. simply leave it open until you're done with it. (There are also non-blocking alternatives if your service has other things to do...)

If the client closes it or opens up a new connection the will have to reauthenticate somehow. (This may be by including a token that you generate for them when they first authenticate - that's your only option if you're using UDP connections).

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