本文介绍了无法从热点连接设备ping主机或通过连接到热点查看主机上的http服务器呈现的网页。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是通过wifi共享文档,没有互联网连接。

我开始使用本教程创建一个热点[这里] [1]

然后我创建一个简单的http服务器使用各种教程在线教程。

最后,http前缀是端口1800上的Laptops ip(我开始热点的那个)。

我成功连接到热点,但是当在客户端浏览器url中输入笔记本电脑的ip和端口时,它没有加载并且最终得到一个超时错误。

当我输入相同的内容时(主机IP和端口号在浏览器网址)我确实收到了网页。



为什么客户端没有显示主机提供的网页空间。



源代码



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

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
}



上述代码的简短摘要:

有三个班级

1)Hotspot

2)热点详情

3)Http服务器



Hotspot创建启动和停止热点。

Hotspot详细信息主要获取所连接设备的所有IP地址。

HTTP服务器运行带有两个前缀127.0.0.1:1800和{My IP Address}的HTTP服务器:1800。



当然在调试文件夹中有一个index.html页面。



当我ping一个连接的IP时设备我得到一个响应,但是当我从客户设备ping主机IP时,我没有收到回复。



此外,网页可以从本地主机获得,但是从连接到热点的设备我得到一个来自chrome的超时错误。



为什么是webpa ge不在客人设备上呈现?



提前致谢。



我尝试过什么:



i尝试ping ip,在 flow得不到响应


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

推荐答案


这篇关于无法从热点连接设备ping主机或通过连接到热点查看主机上的http服务器呈现的网页。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 17:07