Get IP address from Android and IOS Device using .NET MAUI - c#

I am trying to get IP address from android device using .NET MAUI. (Current android framework net6.0-android)
With the below code, I can get the IP with the first launch of the application. And it does not work with following launch of the application unless I reboot my phone.(Tested on Samsung S10+ Android 12)
private void GetIPAddressClicked(object sender, EventArgs e)
{
string interfaceDescription = string.Empty;
var result = new List<IPAddress>();
try
{
var upAndNotLoopbackNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces().Where(n => n.NetworkInterfaceType != NetworkInterfaceType.Loopback
&& n.OperationalStatus == OperationalStatus.Up);
foreach (var networkInterface in upAndNotLoopbackNetworkInterfaces)
{
var iPInterfaceProperties = networkInterface.GetIPProperties();
var unicastIpAddressInformation = iPInterfaceProperties.UnicastAddresses.FirstOrDefault(u => u.Address.AddressFamily == AddressFamily.InterNetwork);
if (unicastIpAddressInformation == null) continue;
result.Add(unicastIpAddressInformation.Address);
interfaceDescription += networkInterface.Description + "---";
}
}
catch (Exception ex)
{
Debug.WriteLine($"Unable to find IP: {ex.Message}");
}
finally
{
string allIpInfo = string.Empty;
foreach (var item in result)
{
allIpInfo += item.ToString() + "---";
}
IPAddress.Text = allIpInfo;
InterfaceName.Text = interfaceDescription;
}
When it works,
interfaceDescription = "------"
allIpInfo = "192.168.50.112---127.0.0.1---"
When it does not work,
interfaceDescription ---> rmnet_data0
allIpInfo ---> 192.0.0.2
I am not sure what is wrong here. How can I fix this? Or is there a better way to get the IP address?
Thanks.

Related

How to find MAC address of Client PC using c# asp.net?

This is my code for find MAC address, but it show same result when I run this in any device?
public string GetMACAddress1()
{
try
{
NetworkInterface[] anics=NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in anics)
{
if (amacaddress == String.Empty)
{
IPInterfaceProperties properties =adapter.GetIPProperties();
amacaddress = adapter.GetPhysicalAddress().ToString();
}
}
return "MAC Address is :- " + amacaddress;
}
catch
{
return "error";
}
}
How can I got this.?

Finding Bluetooth Mac address in Windows10 UWP without pairing

I'm trying to write an app that reads all MAC addresses around on Windows 10 IoT. These lines of code is returning all paired devices even if they aren't turn on.
var selector = BluetoothDevice.GetDeviceSelector();
var devices = await DeviceInformation.FindAllAsync(selector);
listBox.Items.Add(devices.Count);
foreach (var device in devices)
{
listBox.Items.Add(device.Id);
}
And I also found this line of code
await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
This returning null though. Is there any way to scan for all MAC addresses in a Windows 10 universal app?
You are very close to finding the answer of your question. You might try getting a BluetoothDevice instance from the DeviceId property. You will then be able to get all the specific Bluetooth information including the Bluetooth address
var selector = BluetoothDevice.GetDeviceSelector();
var devices = await DeviceInformation.FindAllAsync(selector);
foreach (var device in devices)
{
var bluetoothDevice = await BluetoothDevice.FromIdAsync(device.Id);
if (bluetoothDevice != null)
{
Debug.WriteLine(bluetoothDevice.BluetoothAddress);
}
Debug.WriteLine(device.Id);
foreach(var property in device.Properties)
{
Debug.WriteLine(" " + property.Key + " " + property.Value);
}
}
There is a new approach using BluetoothLEAdvertisementWatcher to scan for all Bluetooth LE device around.
Here is a piece of code I use in my project:
var advertisementWatcher = new BluetoothLEAdvertisementWatcher()
{
SignalStrengthFilter.InRangeThresholdInDBm = -100,
SignalStrengthFilter.OutOfRangeThresholdInDBm = -102,
SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(2000)
};
advertisementWatcher.Received += AdvertisementWatcher_Received;
advertisementWatcher.Stopped += AdvertisementWatcher_Stopped;
advertisementWatcher.Start();
and later
advertisementWatcher.Stop();
advertisementWatcher.Received -= AdvertisementWatcher_Received;
advertisementWatcher.Stopped -= AdvertisementWatcher_Stopped;
private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
//MessAgeChanged(MsgType.NotifyTxt, "FR_NAME:"+ eventArgs.Advertisement.LocalName + "BT_ADDR: " + eventArgs.BluetoothAddress);
string sDevicename = setup.Default.BLEName.Text;
BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress).Completed = async (asyncInfo, asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Completed)
{
if (asyncInfo.GetResults() == null)
{
if (!FailMsg)
{
MessAgeChanged(MsgType.NotifyTxt, "None");
}
}
else
{
BluetoothLEDevice currentDevice = asyncInfo.GetResults();
Boolean contain = false;
foreach (BluetoothLEDevice device in DeviceList.ToArray())/
{
if (device.DeviceId == currentDevice.DeviceId)
{
contain = true;
}
}
if (!contain)
{
byte[] _Bytes1 = BitConverter.GetBytes(currentDevice.BluetoothAddress);
Array.Reverse(_Bytes1);
// The received signal strength indicator (RSSI)
double rssi = eventArgs.RawSignalStrengthInDBm;
DeviceList.Add(currentDevice);
MessAgeChanged(MsgType.NotifyTxt, currentDevice.Name + " " + BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower() + " " + rssi);
DeviceWatcherChanged(MsgType.BleDevice, currentDevice);
}
}
}
};
}

How to set IP address of device connected to Host PC? C# Winform?

I have a Modbus TCP/IP to MODBUS RTU converter , which comes with a default IP of 192.168.0.1 . I need to develop a small c# Winform app to change this device's IP address to any desired IP address. How do I do that?.
You could do it with WMI (Windows Management Instrumentation).
First, you have to add the reference for System.Management to your Project.
Second, you need to find the NetworkInterface for your network connection by name:
using System.Net.NetworkInformation;
using System.Management;
public class NetworkManager
{
public static NetworkInterface GetNetworkInterface(string sName)
{
NetworkInterface NetInterface = null;
// Precondition
if (sName == "") return null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
if (ni.Name == sName)
{
NetInterface = ni;
break;
}
}
return NetInterface;
}
Third, you have to create a ManagementObject for your NetworkInterface:
public static ManagementObject GetNetworkAdapterManagementObject(NetworkInterface NetInterface)
{
ManagementObject oMngObj = null;
// Precondition
if (NetInterface == null) return null;
string sNI = NetInterface.Id;
ManagementClass oMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection oMOC = oMC.GetInstances();
foreach (ManagementObject oMO in oMOC)
{
string sMO = oMO["SettingID"].ToString();
if (sMO == sNI)
{
// Found
oMngObj = oMO;
break;
}
}
return oMngObj;
}
Fours, you can set the ipadress with:
public static bool SetIPAdress(ManagementObject oMO, string[] saIPAdress, string[] saSubnetMask)
{
bool bErg = false;
try
{
// Precondition
if (oMO == null) return false;
if (saIPAdress == null) return false;
if (saSubnetMask == null) return false;
// Get ManagementBaseObject
ManagementBaseObject oNewIP = null;
oNewIP = oMO.GetMethodParameters("EnableStatic");
oNewIP["IPAddress"] = saIPAdress;
oNewIP["SubnetMask"] = saSubnetMask;
// Invoke
oMO.InvokeMethod("EnableStatic", oNewIP, null);
// Alles ok
bErg = true;
}
catch (Exception ex)
{
Console.WriteLine("SetIPAdress failed: " + ex.Message);
}
return bErg;
}
}
Now you can use it, for example in a button click event handler:
private void button1_Click(object sender, EventArgs e)
{
string sConn = "LAN-Verbindung";
NetworkInterface oNI = NetworkManager.GetNetworkInterface(sConn);
ManagementObject oMO = NetworkManager.GetNetworkAdapterManagementObject(oNI);
string sIPAdress = "192.168.1.1";
string sSubnetMask = "255.255.255.0";
string[] saIPAdress = {sIPAdress};
string[] saSubnetMask = {sSubnetMask};
if (NetworkManager.SetIPAdress(oMO, saIPAdress, saSubnetMask))
{
Console.WriteLine("Yes...");
}
}
Depending on the policies on your pc, may be you have to run the program as Administrator...

How do I find the local IP address on a Win 10 UWP project

I am currently trying to port an administrative console application over to a Win 10 UWP app. I am having trouble with using the System.Net.Dns from the following console code.
How can I get the devices IP
Here is the console app code that I am trying to port over.
public static string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily == AddressFamily.InterNetwork)
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
Use this to get host IPaddress in a UWP app, I've tested it:
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
if (localHostName.IPInformation != null)
{
if (localHostName.Type == HostNameType.Ipv4)
{
textblock.Text = localHostName.ToString();
break;
}
}
}
And see the API Doc here
You may try like this :
private string GetLocalIp()
{
var icp = NetworkInformation.GetInternetConnectionProfile();
if (icp?.NetworkAdapter == null) return null;
var hostname =
NetworkInformation.GetHostNames()
.SingleOrDefault(
hn =>
hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
== icp.NetworkAdapter.NetworkAdapterId);
// the ip address
return hostname?.CanonicalName;
}
the answer above is also right
based on answer by #John Zhang, but with fix to not throw LINQ error about multiple matches and return Ipv4 address:
public static string GetFirstLocalIp(HostNameType hostNameType = HostNameType.Ipv4)
{
var icp = NetworkInformation.GetInternetConnectionProfile();
if (icp?.NetworkAdapter == null) return null;
var hostname =
NetworkInformation.GetHostNames()
.FirstOrDefault(
hn =>
hn.Type == hostNameType &&
hn.IPInformation?.NetworkAdapter != null &&
hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId);
// the ip address
return hostname?.CanonicalName;
}
obviously you can pass HostNameType.Ipv6 instead of the Ipv4 which is the default (implicit) parameter value to get the Ipv6 address

DatagramSocket throws Exception while sending to multicast group

I try to send some data to a multicast group. This worked for sometime, but now I get an exception.
The Exception says that the hostname can't be resolved (HRESULT: 0x80072AF9).
The hostname he tries to resolve is the ip address (224.5.6.7). This exception doesn't occurs on my Surface RT but on the Surface Pro.
With this sample I could produce the error:
private async void Test()
{
try
{
var socket = new Windows.Networking.Sockets.DatagramSocket();
var localAdress = CurrentIPAddress();
var port = "40404";
const string M_GROUP = "224.5.6.7";
socket.MessageReceived += (sender, ev) => {
System.Diagnostics.Debugger.Break();
};
await socket.BindEndpointAsync(new HostName(localAdress), port);
socket.JoinMulticastGroup(new HostName(M_GROUP));
//HRESULT: 0x80072AF9
var stream = await socket.GetOutputStreamAsync(
new HostName(M_GROUP),
port);
await stream.WriteAsync(new byte[] { 3 }.AsBuffer());
}
catch (Exception e)
{
System.Diagnostics.Debugger.Break();
throw;
}
}
private string CurrentIPAddress()
{
var icp = NetworkInformation.GetInternetConnectionProfile();
if (icp != null && icp.NetworkAdapter != null)
{
var hostname =
NetworkInformation.GetHostNames()
.SingleOrDefault(
hn =>
hn.IPInformation != null && hn.IPInformation.NetworkAdapter != null
&& hn.IPInformation.NetworkAdapter.NetworkAdapterId
== icp.NetworkAdapter.NetworkAdapterId);
if (hostname != null)
{
// the ip address
return hostname.CanonicalName;
}
}
return string.Empty;
}
The Exception happens when GetOutputStreamAsync is called.
In both Systems the Sockets are bound to an ipv4 address.
Both Systems are up do date. (29. May 2014)
That is a known bug in Windows 8.1: http://social.msdn.microsoft.com/Forums/en-US/908c6c55-fb1d-48ed-8275-835efcca9294/multicast-issue-when-migrating-from-win8-to-win81?forum=winappswithcsharp

Categories

Resources