using System;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
// Reference from http://csharp.net-informations.com/communications/csharp-socket-programming.htm
// Server
namespace test1
{
	class Program
	{
		static void Main(string[] args)
		{
            // IPAddress ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
			System.Net.IPAddress ipaddr = System.Net.IPAddress.Parse(GetLocalIPAddress());
			TcpListener serverSocket = new TcpListener(ipaddr,8888);			
			TcpClient clientSocket = default(TcpClient);
			serverSocket.Start();
			Console.WriteLine(">> Server Started (Waiting for connected ..)");
			clientSocket = serverSocket.AcceptTcpClient();
			Console.WriteLine(">> Accept connection from client");			
			NetworkStream networkStream = clientSocket.GetStream();				
			byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];				
			// byte[] bytesFrom = new byte[10025];
			networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);					
			string dataFromClient = Encoding.ASCII.GetString(bytesFrom);
			dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
			Console.WriteLine(">> Data from client : " + dataFromClient);		
			clientSocket.Close();
			serverSocket.Stop();         
            Console.WriteLine(">> Press any key to exit.");
            Console.ReadLine();
		}		
		static string GetLocalIPAddress()
		{
    		var host = Dns.GetHostEntry(Dns.GetHostName());
    		foreach (var ip in host.AddressList)
    		{
        		if (ip.AddressFamily == AddressFamily.InterNetwork)
        		{
        			Console.WriteLine(">> Server IP Address : " + ip.ToString());
            		return ip.ToString();
        		}
    		}
    		throw new Exception("No network adapters with an IPv4 address in the system!");
		}
	}
}