private WindowsIdentity Authenticate(ref Stream netStream, TcpServerSocketHandler streamManager) { // Use the identity for impersonation etc. NegotiateStream negoServer = null; try { negoServer = new NegotiateStream(netStream); // Block for authentication request TokenImpersonationLevel impLevel = TokenImpersonationLevel.Identification; if (_impersonate) { impLevel = TokenImpersonationLevel.Impersonation; } negoServer.AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, _protectionLevel, impLevel); netStream = negoServer; return((WindowsIdentity)negoServer.RemoteIdentity); } catch { streamManager.SendErrorResponse( String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthenticationFailed")), false); if (negoServer != null) { negoServer.Close(); } throw; } }
public static void AuthenticateClient(TcpClient client) { var networkStream = client.GetStream(); // Create the NegotiateStream. var negotiateStream = new NegotiateStream(networkStream, false); // Combine client and NegotiateStream instance into ClientState. var clientState = new ClientState(negotiateStream, client); // Listen for the client authentication request. negotiateStream.BeginAuthenticateAsServer( EndAuthenticateCallback, clientState ); // Wait until the authentication completes. clientState.Waiter.WaitOne(); clientState.Waiter.Reset(); // Receive encoded message sent by client. negotiateStream.BeginRead( clientState.Buffer, 0, clientState.Buffer.Length, EndReadCallback, clientState); clientState.Waiter.WaitOne(); // Close stream and client. negotiateStream.Close(); client.Close(); }
//<snippet1> public static void AuthenticateClient(TcpClient clientRequest) { NetworkStream stream = clientRequest.GetStream(); // Create the NegotiateStream. NegotiateStream authStream = new NegotiateStream(stream, false); // Save the current client and NegotiateStream instance // in a ClientState object. ClientState cState = new ClientState(authStream, clientRequest); // Listen for the client authentication request. authStream.BeginAuthenticateAsServer( new AsyncCallback(EndAuthenticateCallback), cState ); // Wait until the authentication completes. cState.Waiter.WaitOne(); cState.Waiter.Reset(); authStream.BeginRead(cState.Buffer, 0, cState.Buffer.Length, new AsyncCallback(EndReadCallback), cState); cState.Waiter.WaitOne(); // Finished with the current client. authStream.Close(); clientRequest.Close(); }
private WindowsIdentity Authenticate(ref Stream netStream, TcpServerSocketHandler streamManager) { NegotiateStream stream = null; WindowsIdentity remoteIdentity; try { stream = new NegotiateStream(netStream); TokenImpersonationLevel identification = TokenImpersonationLevel.Identification; if (this._impersonate) { identification = TokenImpersonationLevel.Impersonation; } stream.AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, this._protectionLevel, identification); netStream = stream; remoteIdentity = (WindowsIdentity)stream.RemoteIdentity; } catch { streamManager.SendErrorResponse(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthenticationFailed"), new object[0]), false); if (stream != null) { stream.Close(); } throw; } return(remoteIdentity); }
//<snippet1> public static void AuthenticateClient(TcpClient clientRequest) { NetworkStream stream = clientRequest.GetStream(); // Create the NegotiateStream. NegotiateStream authStream = new NegotiateStream(stream, false); // Perform the server side of the authentication. authStream.AuthenticateAsServer(); // Display properties of the authenticated client. IIdentity id = authStream.RemoteIdentity; Console.WriteLine("{0} was authenticated using {1}.", id.Name, id.AuthenticationType ); // Read a message from the client. byte [] buffer = new byte[2048]; int charLength = authStream.Read(buffer, 0, buffer.Length); string messageData = new String(Encoding.UTF8.GetChars(buffer, 0, buffer.Length)); Console.WriteLine("READ {0}", messageData); // Finished with the current client. authStream.Close(); // Close the client connection. clientRequest.Close(); }
public static void Main(String[] args) { //<snippet2> //<snippet1> // Establish the remote endpoint for the socket. // For this example, use the local machine. IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost"); IPAddress ipAddress = ipHostInfo.AddressList[0]; // Client and server use port 11000. IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); // Create a TCP/IP socket. client = new TcpClient(); // Connect the socket to the remote endpoint. client.Connect(remoteEP); Console.WriteLine("Client connected to {0}.", remoteEP.ToString()); // Ensure the client does not close when there is // still data to be sent to the server. client.LingerState = new LingerOption(true, 0); //<snippet3> // Request authentication. NetworkStream clientStream = client.GetStream(); NegotiateStream authStream = new NegotiateStream(clientStream, false); //</snippet1> // Pass the NegotiateStream as the AsyncState object // so that it is available to the callback delegate. Task authenticateTask = authStream .AuthenticateAsClientAsync() .ContinueWith(task => { Console.WriteLine("Client ending authentication..."); Console.WriteLine("ImpersonationLevel: {0}", authStream.ImpersonationLevel); }); //</snippet2> Console.WriteLine("Client waiting for authentication..."); // Wait until the result is available. authenticateTask.Wait(); // Display the properties of the authenticated stream. AuthenticatedStreamReporter.DisplayProperties(authStream); // Send a message to the server. // Encode the test data into a byte array. byte[] message = Encoding.UTF8.GetBytes("Hello from the client."); Task writeTask = authStream .WriteAsync(message, 0, message.Length) .ContinueWith(task => { Console.WriteLine("Client ending write operation..."); }); //</snippet3> writeTask.Wait(); Console.WriteLine("Sent {0} bytes.", message.Length); // Close the client connection. authStream.Close(); Console.WriteLine("Client closed."); }
//<snippet4> public static void Main(String[] args) { //<snippet3> // Establish the remote endpoint for the socket. // For this example, use the local machine. IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; // Client and server use port 11000. IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); // Create a TCP/IP socket. TcpClient client = new TcpClient(); // Connect the socket to the remote endpoint. client.Connect(remoteEP); Console.WriteLine("Client connected to {0}.", remoteEP.ToString()); // Ensure the client does not close when there is // still data to be sent to the server. client.LingerState = (new LingerOption(true, 0)); // Request authentication. NetworkStream clientStream = client.GetStream(); NegotiateStream authStream = new NegotiateStream(clientStream); // Request authentication for the client only (no mutual authentication). // Authenicate using the client's default credetials. // Permit the server to impersonate the client to access resources on the server only. // Request that data be transmitted using encryption and data signing. authStream.AuthenticateAsClient( (NetworkCredential)CredentialCache.DefaultCredentials, "", ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Impersonation); //</snippet3> DisplayAuthenticationProperties(authStream); DisplayStreamProperties(authStream); if (authStream.CanWrite) { // Encode the test data into a byte array. byte[] message = System.Text.Encoding.UTF8.GetBytes("Hello from the client."); authStream.Write(message, 0, message.Length); authStream.Flush(); Console.WriteLine("Sent {0} bytes.", message.Length); } // Close the client connection. authStream.Close(); Console.WriteLine("Client closed."); }
public static void Main(String[] args) { // Establish the remote endpoint for the socket. // For this example, use the local machine. IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost"); IPAddress ipAddress = ipHostInfo.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork); // Client and server use port 11000. IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); // Create a TCP/IP socket. client = new TcpClient(); // Connect the socket to the remote endpoint. client.Connect(remoteEP); Console.WriteLine("Client connected to {0}.", remoteEP.ToString()); // Ensure the client does not close when there is // still data to be sent to the server. client.LingerState = (new LingerOption(true, 0)); // Request authentication. NetworkStream clientStream = client.GetStream(); NegotiateStream authStream = new NegotiateStream(clientStream, false); // Pass the NegotiateStream as the AsyncState object // so that it is available to the callback delegate. IAsyncResult ar = authStream.BeginAuthenticateAsClient( new AsyncCallback(EndAuthenticateCallback), authStream ); Console.WriteLine("Client waiting for authentication..."); // Wait until the result is available. ar.AsyncWaitHandle.WaitOne(); // Display the properties of the authenticated stream. AuthenticatedStreamReporter.DisplayProperties(authStream); // Send a message to the server. // Encode the test data into a byte array. byte[] message = Encoding.UTF8.GetBytes("Hello from the client."); ar = authStream.BeginWrite(message, 0, message.Length, new AsyncCallback(EndWriteCallback), authStream); ar.AsyncWaitHandle.WaitOne(); Console.WriteLine("Sent {0} bytes.", message.Length); // Close the client connection. authStream.Close(); Console.WriteLine("Client closed."); Console.Read(); }
public static void AuthenticateClient(TcpClient clientRequest) { NetworkStream stream = clientRequest.GetStream(); var authStream = new NegotiateStream(stream, false); var builder = new StringBuilder(); try { authStream.AuthenticateAsServer( CredentialCache.DefaultNetworkCredentials, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); DisplayProperties(authStream); var buffer = new byte[65536]; int bytesRead; while (true) { bytesRead = authStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } builder.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); } IIdentity id = authStream.RemoteIdentity; string message = builder.ToString(); Console.WriteLine("{0} sent a message of length: {1}", id.Name, message.Length); Console.WriteLine("Client disconnected."); Console.WriteLine(); } catch (Exception e) { Console.WriteLine($"Client message exception: {e.ToString()}"); } finally { authStream.Close(); } }
//<snippet1> public static void AuthenticateClient(TcpClient clientRequest) { NetworkStream stream = clientRequest.GetStream(); // Create the NegotiateStream. NegotiateStream authStream = new NegotiateStream(stream, false); // Save the current client and NegotiateStream instance // in a ClientState object. ClientState cState = new ClientState(authStream, clientRequest); // Listen for the client authentication request. Task authTask = authStream .AuthenticateAsServerAsync() .ContinueWith(task => { EndAuthenticateCallback(cState); }); // Any exceptions that occurred during authentication are // thrown by the EndAuthenticateAsServer method. try { // This call blocks until the authentication is complete. authTask.Wait(); } catch (AuthenticationException e) { Console.WriteLine(e); Console.WriteLine("Authentication failed - closing connection."); return; } catch (Exception e) { Console.WriteLine(e); Console.WriteLine("Closing connection."); return; } Task <int> readTask = authStream .ReadAsync(cState.Buffer, 0, cState.Buffer.Length); readTask .ContinueWith((task) => { EndReadCallback(cState, task.Result); }) .Wait(); // Finished with the current client. authStream.Close(); clientRequest.Close(); }
public static void Main() { NegotiateStream negotiateStream = null; try { // Set the TcpListener on port 13000. Int32 port = 13000; IPAddress localAddr = IPAddress.Loopback; // TcpListener server = new TcpListener(port); TcpListener server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[256]; String data = null; // Enter the listening loop. while (true) { Console.Write("Waiting for a connection... "); // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); data = null; // Get a stream object for reading and writing // Wrap it in a NegotiateStream. negotiateStream = new NegotiateStream(client.GetStream()); negotiateStream.AuthenticateAsServer(); if (negotiateStream.IsAuthenticated) { Console.WriteLine( "IsAuthenticated: {0}", negotiateStream.IsAuthenticated); Console.WriteLine( "IsMutuallyAuthenticated: {0}", negotiateStream.IsMutuallyAuthenticated); Console.WriteLine( "IsEncrypted: {0}", negotiateStream.IsEncrypted); Console.WriteLine( "IsSigned: {0}", negotiateStream.IsSigned); Console.WriteLine( "IsServer: {0}", negotiateStream.IsServer); IIdentity remoteIdentity = negotiateStream.RemoteIdentity; Console.WriteLine( "Client identity: {0}", remoteIdentity.Name); Console.WriteLine( "Authentication Type: {0}", remoteIdentity.AuthenticationType); } int i; // Loop to receive all the data sent by the client. while ( (i = negotiateStream.Read(bytes, 0, bytes.Length)) != 0) { // Translate data bytes to a string. // The encoding used is application specific. data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine("Received: {0}", data); // Process the data sent by the client. data = data.ToUpper( System.Globalization.CultureInfo.CurrentCulture); byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); // Send back a response. negotiateStream.Write(msg, 0, msg.Length); Console.WriteLine("Sent: {0}", data); } } } catch (AuthenticationException ex) { Console.WriteLine(ex.Message); } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ex) { Console.WriteLine(ex.Message); } finally { if (negotiateStream != null) { negotiateStream.Close(); } } Console.WriteLine("\nHit enter to continue..."); Console.Read(); }
static void Connect( String server, String message, string servicePrincipalName) { NegotiateStream negotiateStream = null; try { // Create a TcpClient. // Note, for this client to work you need to have a TcpServer // connected to the same address as specified by the server, // port combination. Int32 port = 13000; TcpClient client = new TcpClient(server, port); // Translate the message into a byte array. // The encoding used is application specific. Byte[] data = System.Text.Encoding.ASCII.GetBytes(message); // Get a client stream for reading and writing. // Wrap it in a NegotiateStream. negotiateStream = new NegotiateStream(client.GetStream()); // This example uses the SPN which is required for Kerberos. // If you don't know your service principal name, you can do // NTLM authentication by commenting out the line below negotiateStream.AuthenticateAsClient( CredentialCache.DefaultNetworkCredentials, servicePrincipalName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Impersonation); // And then uncomment this line // authenticatedStream.AuthenticateAsClient(); if (negotiateStream.IsAuthenticated) { Console.WriteLine( "IsAuthenticated: {0}", negotiateStream.IsAuthenticated); Console.WriteLine( "IsMutuallyAuthenticated: {0}", negotiateStream.IsMutuallyAuthenticated); Console.WriteLine( "IsEncrypted: {0}", negotiateStream.IsEncrypted); Console.WriteLine( "IsSigned: {0}", negotiateStream.IsSigned); Console.WriteLine( "IsServer: {0}", negotiateStream.IsServer); } // Send the message to the connected TcpServer. negotiateStream.Write(data, 0, data.Length); Console.WriteLine("Sent: {0}", message); // Receive the TcpServer.response: // Buffer to store the response bytes. data = new Byte[256]; // String to store the response ASCII representation. String responseData = String.Empty; // Read the first batch of the TcpServer response bytes. Int32 bytes = negotiateStream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); Console.WriteLine("Received: {0}", responseData); } catch (AuthenticationException ex) { Console.WriteLine(ex.Message); } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ex) { Console.WriteLine(ex.Message); } finally { if (negotiateStream != null) { negotiateStream.Close(); } } Console.WriteLine("\n Press Enter to continue..."); Console.Read(); }
static void Main(string[] args) { if (args.Length < 3) { Console.WriteLine("Usage: NegotiateClient [NegotiateServer DNS/IP] [Port] [Message]"); return; } string host = args[0]; string port = args[1]; string message = args[2]; NegotiateStream negotiateStream = null; try { IPAddress serverIP = Dns.Resolve(host).AddressList[0]; // 使用伺服端之IPEndPoint IPEndPoint serverhost = new IPEndPoint(serverIP, Int32.Parse(port)); TcpClient tcpClient = new TcpClient(); // 建立用戶端與伺服端的連線 tcpClient.Connect(serverhost); // 建立支援用戶端與伺服端間交涉安全性通訊協定之資料串流 negotiateStream = new NegotiateStream(tcpClient.GetStream()); // 用戶端登入網路或伺服端的帳號與密碼 NetworkCredential credential = CredentialCache.DefaultNetworkCredentials; // 服務主要名稱(Service Primary Name),代表驗證伺服端的識別名稱 string targetName = "domain\\user"; // 已驗證資料串流所要求的安全性服務 // 加密並簽署資料,以協助確保資料傳輸的機密性與完整性 ProtectionLevel requiredProtectionLevel = ProtectionLevel.EncryptAndSign; // 設定伺服端處理序如何模擬用戶端之認證 // 可在本機模擬用戶端的安全性內容,但無法在遠端模擬用戶端的安全性內容 TokenImpersonationLevel allowedImpersonationLevel = TokenImpersonationLevel.Impersonation; // 由用戶端呼叫驗證連接中之用戶端,並選擇性驗證伺服端 negotiateStream.AuthenticateAsClient(credential, targetName, requiredProtectionLevel, allowedImpersonationLevel); // 或是 // negotiateStream.AuthenticateAsClient(); // 判斷驗證(Authentication)是否成功 if (negotiateStream.IsAuthenticated) { Console.WriteLine("IsAuthenticated: {0}", negotiateStream.IsAuthenticated); Console.WriteLine("IsEncrypted: {0}", negotiateStream.IsEncrypted); Console.WriteLine("IsMutuallyAuthenticated: {0}", negotiateStream.IsMutuallyAuthenticated); Console.WriteLine("IsServer: {0}", negotiateStream.IsServer); Console.WriteLine("IsSigned: {0}", negotiateStream.IsSigned); } // 判斷串流是否支援寫入功能 if (negotiateStream.CanWrite) { // 設定傳送資料緩衝區 byte[] msg = Encoding.ASCII.GetBytes(message); // 將資料寫入資料串流中 negotiateStream.Write(msg, 0, msg.Length); Console.WriteLine("傳送的資料內容: " + "\r\n" + "{0}", message + "\r\n"); } else { Console.WriteLine("串流不支援寫入功能."); } // 判斷串流是否支援讀取功能 if (negotiateStream.CanRead) { // 設定接收資料緩衝區 byte[] bytes = new Byte[1024]; // 自資料串流中讀取資料 int bytesReceived = negotiateStream.Read(bytes, 0, bytes.Length); string data = Encoding.ASCII.GetString(bytes, 0, bytesReceived); Console.WriteLine("接收的資料內容: " + "\r\n" + "{0}", data + "\r\n"); } else { Console.WriteLine("串流不支援讀取功能."); } } catch (AuthenticationException ex) { Console.WriteLine(ex.Message); } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ex) { Console.WriteLine(ex.Message); } finally { if (negotiateStream != null) { // 關閉串流 negotiateStream.Close(); } } Console.WriteLine("Press Enter to exit."); Console.Read(); }
static string ProcessMessage(string[] args) { // If no arguments supplied, default to show help. if (args.Count() == 0) { args = new string[] { "help" } } ; // Look to see what local / library commands there are. var command = ArgsCommand.Create(args); // Generally, the only commands processed locally by the // cli are 'api' and 'script'. The API command sets the // service end point, and the SCRIPT command runs a // script of commands. All other commands are processed // on the server if (args[0].Equals("api", StringComparison.OrdinalIgnoreCase)) { return(command.Execute()); } else if (args[0].Equals("script", StringComparison.OrdinalIgnoreCase)) { var script = command.Execute(); var lines = Regex.Split(script, "\r\n|\r|\n"); string output = ""; foreach (var line in lines) { var l = line.Trim(); if (l.Length > 0 && l.Substring(0, 1) != "#") { output += ProcessMessage(line.ParseArgs()) + Environment.NewLine; } } return(output); } else { string result = string.Empty; string host = (string)Properties.Settings.Default["host"]; int port = (int)Properties.Settings.Default["port"]; // must be processed on server. TcpClient client = new TcpClient(); //client.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); // Parse the host value. Can be host name or IPv4 address. IPAddress addr = null; if (!IPAddress.TryParse(host, out addr)) { // if failed, try dns lookup var hostEntry = Dns.GetHostEntry(host); foreach (var item in hostEntry.AddressList) { // Get the first IPv4 address. if (item.AddressFamily == AddressFamily.InterNetwork) { addr = item; break; } } if (addr == null) { throw new Exception("Invalid host."); } } IPEndPoint serverEndPoint = new IPEndPoint(addr, port); client.Connect(serverEndPoint); // Ensure the client does not close when there is // still data to be sent to the server. client.LingerState = (new LingerOption(true, 0)); // Request authentication NetworkStream clientStream = client.GetStream(); NegotiateStream authStream = new NegotiateStream(clientStream, false); // Pass the NegotiateStream as the AsyncState object // so that it is available to the callback delegate. authStream.AuthenticateAsClient(); // Convert client arguments to a byte array BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, args); byte[] buffer = new byte[ms.Length]; buffer = ms.ToArray(); // Send a message to the server. // Encode the test data into a byte array. authStream.Write(buffer, 0, buffer.Length); // get the response byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { //blocks until a client sends a message bytesRead = authStream.Read(message, 0, 4096); } catch { //a socket error has occured break; } if (bytesRead == 0) { //the client has disconnected from the server break; } ASCIIEncoding encoder = new ASCIIEncoding(); result += encoder.GetString(message, 0, bytesRead); if (bytesRead < 4096) { break; } } // Close the client connection. authStream.Close(); return(result); } } }
public static void Main(string[] args) { if (args.Length < 3 || args.Length == 4) { DisplayUsage(); return; } string server = args[0]; int port = int.Parse(args[1]); string target = args[2]; string userName = null; string password = null; string domain = null; if (args.Length > 3) { userName = args[3]; password = args[4]; if (args.Length == 6) { domain = args[5]; } } try { var client = new TcpClient(); client.Connect(server, port); Console.WriteLine($"Client connected to {server}:{port}"); // Ensure the client does not close when there is still data to be sent to the server. client.LingerState = new LingerOption(true, 0); // Request authentication. NetworkStream clientStream = client.GetStream(); var authStream = new NegotiateStream(clientStream, false); var credential = (userName == null) ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(userName, password, domain); Console.Write("Client waiting for authentication..."); authStream.AuthenticateAsClient( credential, target, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); Console.WriteLine("done."); DisplayProperties(authStream); // Send a message to the server. var writer = new StreamWriter(authStream); var clientMessage = new string('A', 65536); byte[] message = Encoding.UTF8.GetBytes(clientMessage); authStream.Write(message, 0, message.Length); Console.WriteLine("Sent {0} bytes.", message.Length); // Close the client connection. authStream.Close(); Console.WriteLine("Closing client."); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
private static void Connect(string username = null, string password = null, string host = "localhost", int addressIndex = 1, int port = 11000) { // Get IP address. var ipAddress = Dns.GetHostEntry(host).AddressList[addressIndex]; // Get remote end point. var endPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. _client = new TcpClient(); // Connect the socket to the remote endpoint. _client.Connect(endPoint); Logging.Log($"Client successfully connected to {endPoint}."); // Keep connection alive if transfer isn't complete. _client.LingerState = new LingerOption(true, 0); // Get negotiation stream from client. var negotiateStream = new NegotiateStream(_client.GetStream(), false); // Pass the NegotiateStream as the AsyncState object // so that it is available to the callback delegate. IAsyncResult asyncResult; // If username/password provided, use as credentials. if (username != null && password != null) { asyncResult = negotiateStream.BeginAuthenticateAsClient( new NetworkCredential("username", "password"), host, EndAuthenticateCallback, negotiateStream); } else { // Use Identification ImpersonationLevel asyncResult = negotiateStream.BeginAuthenticateAsClient( EndAuthenticateCallback, negotiateStream ); } Logging.Log("Client attempting to authenticate."); // Await result. asyncResult.AsyncWaitHandle.WaitOne(); // Send encoded test message to server. var message = Encoding.UTF8.GetBytes("Hello, it's me, the client!"); asyncResult = negotiateStream.BeginWrite( message, 0, message.Length, EndWriteCallback, negotiateStream); // Await result. asyncResult.AsyncWaitHandle.WaitOne(); Logging.Log($"Successfully sent message containing {message.Length} bytes."); // Close the client connection. negotiateStream.Close(); Logging.Log("Client closed."); }
public void ServerThreadProc() { NegotiateStream negotiateStream = null; while (true) { try { // 處理用戶端連線 tcpClient = tcpListener.AcceptTcpClient(); // 取得本機相關的網路資訊 IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint; // 以Client屬性取得用戶端之Socket物件 Socket clientSocket = tcpClient.Client; // 取得連線用戶端相關的網路連線資訊 IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint; Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString()); Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString()); // 建立支援用戶端與伺服端間交涉安全性通訊協定之資料串流 negotiateStream = new NegotiateStream(tcpClient.GetStream()); // 由伺服端呼叫驗證連接中之用戶端,並選擇性驗證伺服端 negotiateStream.AuthenticateAsServer(); // 判斷驗證(Authentication)是否成功 if (negotiateStream.IsAuthenticated) { System.Security.Principal.IIdentity remoteIdentity = negotiateStream.RemoteIdentity; Console.WriteLine("Client identity: {0}", remoteIdentity.Name); Console.WriteLine("Authentication Type: {0}", remoteIdentity.AuthenticationType); Console.WriteLine("IsAuthenticated: {0}", negotiateStream.IsAuthenticated); Console.WriteLine("IsMutuallyAuthenticated: {0}", negotiateStream.IsMutuallyAuthenticated); Console.WriteLine("IsEncrypted: {0}", negotiateStream.IsEncrypted); Console.WriteLine("IsSigned: {0}", negotiateStream.IsSigned); Console.WriteLine("IsServer: {0}", negotiateStream.IsServer); } // 判斷串流是否支援讀取功能 if (negotiateStream.CanRead) { byte[] bytes = new byte[1024]; // 自資料串流中讀取資料 int bytesReceived = negotiateStream.Read(bytes, 0, bytes.Length); string data = Encoding.ASCII.GetString(bytes, 0, bytesReceived); Console.WriteLine("接收的資料內容: " + "\r\n" + "{0}", data + "\r\n"); } else { Console.WriteLine("串流不支援讀取功能."); } // 判斷串流是否支援寫入功能 if (negotiateStream.CanWrite) { // 測試用 string htmlBody = "<html><head><title>Send Test</title></head><body><font size=2 face=Verdana>Sent OK.</font></body></html>"; string htmlHeader = "HTTP/1.0 200 OK" + "\r\n" + "Server: HTTP Server 1.0" + "\r\n" + "Content-Type: text/html" + "\r\n" + "Content-Length: " + htmlBody.Length + "\r\n" + "\r\n"; string htmlContent = htmlHeader + htmlBody; // 設定傳送資料緩衝區 byte[] msg = Encoding.ASCII.GetBytes(htmlContent); // 將資料寫入資料串流中 negotiateStream.Write(msg, 0, msg.Length); Console.WriteLine("傳送的資料內容: " + "\r\n" + "{0}", Encoding.UTF8.GetString(msg, 0, msg.Length) + "\r\n"); } else { Console.WriteLine("串流不支援寫入功能."); } } catch (AuthenticationException aex) { Console.WriteLine(aex.StackTrace.ToString()); } catch (SocketException ex) { Console.WriteLine(ex.StackTrace.ToString()); } catch (IOException ioex) { Console.WriteLine(ioex.StackTrace.ToString()); } finally { if (negotiateStream != null) { // 關閉串流 negotiateStream.Close(); } } } }