我有一个.NetCore c#应用程序。我在运行Raspbian的Raspberry Pi设备中使用它。
我正在尝试获取我分配的DHCP IP地址。
我试过很多东西。
它们都返回127.0.0.1。
这是使用web套接字。服务器是用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);
}
告诉我"类型或命名空间名称'Networking'在命名空间'System.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套接字连接不起作用
我没有依赖.Net Core库/框架,而是在谷歌上搜索linux命令来获取ip地址,因为我知道它会这样做。如果我打开Pi上的终端窗口并键入:
hostname -I
它将返回ip地址。
因此,我的下一步是从C#中运行这个linux命令。
为此,我可以使用进程类并重新绘制输出:
//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
}