Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My objective was to share documents over wifi,without internet connection.
I started by creating a hotspot using this tutorial [here][1]
Then i created a simple http server Using various tutorials online tutorial.
Finally the http prefix is the Laptops ip(The one i started hotspot on) on port 1800.
I did connect succesfully to the hotspot,but when inputing the laptops ip and port in the client browser url it does not load and finnaly get a timed out error.
when i input the same (host ip and port number in the browser url )i do get the webpage.

Why is the client not showing the webapage being served by the host.

The source code

C#
class Program
{
   #region Main
   static void Main(string[] args)
   {
      Console.WriteLine("Starting Hotspot and http server");
      var th = new Task(() =>
      {
         Hotspot hotSpot = new Hotspot();
         hotSpot.CreateHotSpot("Test", "123456789");
         hotSpot.StartHotSpot();

         String ip = hotSpot.getIp();

         HttpServer httpServer = new HttpServer(ip);

         httpServer.Start();
      });
      th.Start();
      Console.ReadLine();
   }
   #endregion

   /// <summary>
   /// Create ,start ,stop Hotspot.
   /// share internet at the same time
   /// </summary>
   #region Hotspot
   class Hotspot
   {
      private string message = "";
      private dynamic netsharingmanager = null;
      private dynamic everyConnection = null;
      private bool hasnetsharingmanager = false;

      ProcessStartInfo ps = null;

      #region constructor
      public Hotspot()
      {
         ps = new ProcessStartInfo("cmd.exe");
         ps.UseShellExecute = false;
         ps.RedirectStandardOutput = true;
         ps.CreateNoWindow = true;
         ps.FileName = "netsh";


         //sharing 
         netsharingmanager = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.HNetShare.1"));
         if (netsharingmanager == null)
         {
            Console.WriteLine( "HNetCfg.HNetShare.1 was not found \n");
            hasnetsharingmanager = true;
         }
         else
         { hasnetsharingmanager = false; }

         if (netsharingmanager.SharingInstalled == false)
         {
            Console.WriteLine( "Sharing on this platform is not available \n");
            hasnetsharingmanager = false;
         }
         else
         { hasnetsharingmanager = true; }

         if (hasnetsharingmanager)
         { everyConnection = netsharingmanager.EnumEveryConnection; }
      }
      #endregion

      //check internet
      #region Check for internet
      public static bool CheckForInternetConnection()
      {
         try
         {
            using (var client = new WebClient())
            {
               using (client.OpenRead("https://google.com/"))
               { return true; }
            }
         }
         catch { return false; }
      }
      #endregion

      #region start Hotspot
      public void StartHotSpot()
      {
         ps.Arguments = "wlan start hosted network";
         ExecuteCommand(ps);
         Console.WriteLine("Starting Hotspot");

         //check for connected clients
         var th = new Task(() =>
         {
            while (true)
            {
               HotSpotDetails details = new HotSpotDetails();
               List<String> MacAddr = details.Mac_connected_devices();

               Console.WriteLine("\n\n---------------------------------");
               foreach (var item in MacAddr)
               {
                  Console.WriteLine("Connected Device Mac = {0}", item);
               }
               Console.WriteLine("---------------------------------\n\n");
               Thread.Sleep(100000);
            }
         });
         th.Start();
      }
      #endregion

      #region Create hot spot
      public void CreateHotSpot(string ssid_par, string key_par)
      {
         ps.Arguments = string.Format("wlan set hostednetwork mode=allow ssid={0} key={1}", ssid_par, key_par);
         ExecuteCommand(ps);
         Console.WriteLine("Creating hotspot name {0}",ssid_par);
      }
      #endregion

      #region Stop hotspot
      public void stop()
      {
         ps.Arguments = "wlan stop hosted network";
         ExecuteCommand(ps);
      }
      #endregion

      #region  shareinternet
      public void Shareinternet(string pubconnectionname, string priconnectionname, bool isenabled)
      {
         bool hascon = false;
         dynamic thisConnection = null;
         dynamic connectionprop = null;

         if (everyConnection == null)
         {
            everyConnection = netsharingmanager.EnumEveryConnection;
         }
         try
         {
            foreach (dynamic connection in everyConnection)
            {
               thisConnection = netsharingmanager.INetSharingConfigurationForINetConnection(connection);
               connectionprop = netsharingmanager.NetConnectionProps(connection);

               Console.WriteLine("connectionprop name = {0} and pubconnectionname = {1}", connectionprop.name, pubconnectionname);
               if (connectionprop.name == pubconnectionname) //public connection
               {
                  hascon = true;
                  Console.WriteLine( string.Format("Setting ICS Public  {0} on connection: {1}\n", isenabled, pubconnectionname));
                  Console.WriteLine("Setting ICS Public  {0} on connection: {1}\n", isenabled, pubconnectionname);
                  if (isenabled)
                  {
                     thisConnection.EnableSharing(0);
                  }
                  else
                  {
                     thisConnection.DisableSharing();
                  }
               }
               if (connectionprop.Name == priconnectionname) //private connection
               {
                  hascon = true;
                  Console.WriteLine( string.Format("Setting ICS Private  {0} on connection: {1}\n", isenabled, pubconnectionname));
                  Console.WriteLine("Setting ICS Private  {0} on connection: {1}\n", isenabled, pubconnectionname);
                  if (isenabled)
                  {
                     thisConnection.EnableSharing(1);
                  }
                  else
                  {
                     thisConnection.DisableSharing();
                  }
               }
               if (!hascon)
               {
                  this.message += "no connection found";
                  Console.WriteLine("no connection found");
               }
            }
         }
         catch (Exception e)
         {
            Console.WriteLine("Hey an err in hotspot {0}", e);
         }
      }
      #endregion

      #region
      public string getIp()
      {
         string host_name = Dns.GetHostName();
         string ip = string.Empty;
         var host = Dns.GetHostEntry(host_name);
         foreach (var ip_ in host.AddressList)
         {
            if (ip_.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
               ip = ip_.ToString();
            }
         }
         Console.WriteLine("\n -->my host name is {0} and my ip is {1} ", host_name, ip);
         return ip;
      }
      #endregion

      #region Execute command
      private void ExecuteCommand(ProcessStartInfo ps)
      {
         bool isExecuted = false;
         try
         {
            using (Process p = Process.Start(ps))
            {
               message += p.StandardOutput.ReadToEnd() + "\n";
               p.WaitForExit();
               isExecuted = true;
            }
         }
         catch (Exception e)
         {
            message = "errorr -- >";
            message += e.Message;
            isExecuted = false;
         }
      }
      #endregion
   }
   #endregion

   /// <summary>
   /// get the hotspot details eg connected clients
   /// </summary>
   #region Hotspot Details
   class HotSpotDetails
   {
      //mac address list
      List<String> mac_address_list = new List<string>();
      #region GetMacAddr upto
      private List<string> GetMacAddr(string output)
      {
         //split_string.Substring(0, split_string.LastIndexOf(uptoword));

         string mac = string.Empty;
         List<string> mac_ad = new List<string>();

         string[] lines = output.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
         foreach (string line in lines)
         {
            if (line.Contains("Authenticated")) //"Number of clients"))
            {
               mac = line.Substring(0, line.LastIndexOf("Authenticated"));
               mac_ad.Add(mac.Replace(" ", string.Empty));
            }
         }
         return mac_ad;
      }
      #endregion

      #region get mac address of connected devices 
      public List<String> Mac_connected_devices()
      {
         String output = Console_command("netsh", "wlan show hosted");
         // Console.WriteLine("1------>{0}", output);
         mac_address_list = GetMacAddr(output);
         foreach (string item in mac_address_list)
         {
            Console.WriteLine("mac list item-number  = {0}", item);
         }
         return mac_address_list;
      }
      #endregion
      
      #region command line func 
      private string Console_command(string command, string args)
      {
         string output = string.Empty;

         ProcessStartInfo processStartInfo = new ProcessStartInfo(command, args);
         processStartInfo.RedirectStandardOutput = true;
         processStartInfo.UseShellExecute = false;

         processStartInfo.CreateNoWindow = true;

         Process proc = new Process
         {
            StartInfo = processStartInfo
         };

         proc.Start();
         output = proc.StandardOutput.ReadToEnd();
         return output;
      }
      #endregion
   }
   #endregion

   /// <summary>
   /// start and stop the http server at port 1800.
   /// </summary>
   #region HttpServer
   class HttpServer
   {
      public static HttpListener listener = new HttpListener();
      int port = 1800;
      String MyIp;
      Socket serverSocket = null;
      int backlog = 4;
      List<Socket> client = new List<Socket>();
      byte[] Buffer = new byte[1024];

      public HttpServer(String IpAddress)
      {
         this.MyIp = IpAddress;
         serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      }

      //start http server
      public void Start()
      {
         System.Console.WriteLine("http://localhost:{0}/", port);
         System.Console.WriteLine("http://{0}:{1}/", MyIp, port);

         // String Localformart = String.Format("http://localhost:{0}/", port);
         String Gloabalformart = String.Format("http://{0}:{1}/", MyIp, port);

         //add prefix
         // listener.Prefixes.Add(Localformart);
         listener.Prefixes.Add(Gloabalformart);

         if (listener.IsListening)
         { listener.Stop(); }

         listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;

         listener.Start();

         if (listener.IsListening)
         { Console.WriteLine("Http serever listening"); }
         else { Console.WriteLine("Http serever not listening ?"); }

         int requestCounter = 0;

         while (listener.IsListening)
         {
            try
            {
               HttpListenerContext context = listener.GetContext();
               HttpListenerResponse response = context.Response;

               requestCounter++;
               Console.WriteLine("Request counter {0}", requestCounter);
               //webpage requested by browser
               String WebPage = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath; //+ "webpage\\"; // String.Empty;

               Console.WriteLine("Path to wbpage = {0} \n", WebPage);
               if (string.IsNullOrEmpty(WebPage))
               {
                  WebPage = "index.html";
               }

               // TextReader tr = new StreamReader(WebPage);
               FileStream tr = new FileStream(WebPage, FileMode.Open, FileAccess.ReadWrite);

               using (BinaryReader rds = new BinaryReader(tr))
               {
                  var message = rds.ReadBytes(Convert.ToInt32(tr.Length));
                  //transform into byte array
                  // byte[] buffer = Encoding.UTF8.GetBytes(message);

                  //set up the message lent
                  response.ContentLength64 = message.Length;
                  //create a stream to send the message
                  Stream st = response.OutputStream;
                  st.Write(message, 0, message.Length);
                  //close the connection
                  context.Response.Close();
               }
            }
            catch (Exception e)
            {
               Console.WriteLine("Error in Http server is listening");
            }
         }
      }
   }
   #endregion
}

A brief summary of the above code:
There are three classes
1)Hotspot
2)Hotspot Details
3)Http server

The Hotspot creates starts and stops the Hotspot.
The Hotspot details primarily gets all the IP address of connected devices.
The HTTP server runs HTTP server with two prefixes 127.0.0.1:1800 and {My IP Address}:1800.

Of course there exists a index.html page in the debug folder.

When i ping the Ip of a connected devices i get a response however when i ping the host ip from a guest device i do not get a response.

In addition the webpage is rendered okay from the localhost but from the device connected to the hotspot i get a timed out error from chrome.

Why is the webpage not rendered on guest device ?

Thanks in advance.

What I have tried:

i have tried pinging the ip,asked on stack over flow gotten no response
Posted
Updated 7-Jul-18 23:53pm
v2

1 solution

If you can't ping the host from the client, nothing else matters. This has nothing to do with the code or the web server setup and everything to do with the network setup, which we know absolutely nothing about.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900