代码之家  ›  专栏  ›  技术社区  ›  Andrew Simpson

获取Raspbery Pi的DHCP IP地址

  •  0
  • Andrew Simpson  · 技术社区  · 6 年前

    我有一个.NetCore c#应用程序。 我在一个运行覆盆子的设备中使用它。

    我正在尝试获取分配的DHCP IP地址。

    我试过很多东西。

    它们都返回127.0.0.1。

    这是在使用网络套接字。服务器用c写,客户端用JS写。

    除了常见的例子之外,还有什么想法吗?

    最近的尝试:

      public void GetIPAddress()
      {
         List<string> IpAddress = new List<string>();
            var Hosts = System.Windows.Networking.Connectivity.NetworkInformation.GetHostNames().ToList();
            foreach (var Host in Hosts)
            {
                string IP = Host.DisplayName;
                IpAddress.Add(IP);
            }
            IPAddress address = IPAddress.Parse(IpAddress.Last());
            Console.WriteLine(address);
        }
    

    告诉我,“命名空间”Stask.Windows中不存在类型或命名空间名称“联网”(您是否缺少程序集引用?)

        public static string GetLocalIPAddress()
        {
            var localIP = "";
            try
            {
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        localIP = ip.ToString();
                        Console.WriteLine(localIP);
                        //break;
                    }
                }
            }
            catch ( Exception e )
            {
                Console.WriteLine( e );
                Environment.Exit( 0 );
            }
            return localIP;
        }
    

    返回127.0.0.1

    还应该指出使用127.0.0.1作为web套接字连接由于某些原因不起作用

    1 回复  |  直到 6 年前
        1
  •  0
  •   Andrew Simpson    6 年前

    我没有依赖.Net核心库/框架,而是通过谷歌linux命令获取ip地址,因为我知道它会这么做。 如果我打开Pi上的终端窗口并键入:

    hostname -I
    

    它将返回ip地址。

    所以,我的下一步是在C#中运行这个linux命令。

    为此,我可以使用process类并重新输入输出:

    //instantiate a new process with c# app
    var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "hostname",  //my linux command i want to execute
                Arguments = "-I",  //the argument to return ip address
                UseShellExecute = false,
                RedirectStandardOutput = true,  //redirect output to my code here
                CreateNoWindow = true  /do not show a window
            }
        };
    
        proc.Start();  //start the process
        while (!proc.StandardOutput.EndOfStream)  //wait until entire stream from output read in
        {
            Console.WriteLine( proc.StandardOutput.ReadLine());  //this contains the ip output                    
        }