Reputation: 7324
I have a .NetCore c# app. I am using it in a Raspberry Pi device running Raspbian.
I am trying to get my assigned DHCP IP address.
I have tried many things.
They all return 127.0.0.1.
This is using web sockets. The server is written in c# and client is written in JS.
Any ideas apart from the usual examples out there?
Latest attempts:
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);
}
Tells me that "The type or namespace name 'Networking' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)"
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;
}
Returns 127.0.0.1
should also point out that using 127.0.0.1 as the web socket connection does not work for some reason
Upvotes: 0
Views: 599
Reputation: 7324
Rather than rely on .Net Core libraries/framework I instead googled linux commands to get the ip address as I know it does this. If I open a Terminal window on the Pi and type in:
hostname -I
it will return the ip address.
So, my next step was to run this linux command from within C#.
For this I can use the process class and redirct the output:
//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
}
Upvotes: 1