Retrieving RSSI value of connected Wireless device - c#

I want to develop an application which can list all the connected devices to my wifi network and their RSSI values.Could some one tell me how to approach this.Any sample codes would be of help and preferabbly in c sharp.Thanks.
using System.DirectoryServices;
...
List<String> _ComputerNames = new List<String>();
String _ComputerSchema = "Computer";
DirectoryEntry _WinNTDirectoryEntries = new DirectoryEntry("WinNT:");
foreach (DirectoryEntry _AvailDomains in _WinNTDirectoryEntries.Children)
{
foreach (DirectoryEntry _PCNameEntry in _AvailDomains.Children)
{
if (_PCNameEntry.SchemaClassName.ToLower().Contains(_ComputerSchema.ToLower()))
{
_ComputerNames.Add(_PCNameEntry.Name);
}
}
}
This code lists the connected devices but how to get the RSSI value of these devices.

Related

C# SimpleWifi can't connect to an unknown network

I can't connect to wifi networks that the PC doesn't know. If I manually connect first, then the program is able to connect programmatically as long as I don't click on "Forget".
If the network is not known then the ap.Connect(authRequest) returns null.
How can I connect to a wifi network programmatically that the pc doesn't know yet?
var accessPoints = wifi.GetAccessPoints();
List<string> accessPointNames = new List<string>();
foreach (AccessPoint ap in accessPoints)
{
accessPointNames.Add(ap.Name);
string fSSID = "test1234";
if (ap.Name == fSSID)
{
AuthRequest authRequest = new AuthRequest(ap)
{
Password = "12345678"
};
if (ap.Connect(authRequest))
Console.WriteLine("connected");
else
Console.WriteLine("disconnected");
break;
}
}

How to get Physical device IDs of RFID readers using WMI?

Reading RFID's Physical Device Object Name through Serial Port using WMI in C#
I'm setting up a C# code to read signals from different RFID readers. So, I want to get Physical Device ID to recognize which device is sending which signal. So I'm trying to read device information through WMI which has more than 13xx classes.
code.
ManagementObjectSearcher objSearcher = new ManagementObjectSearcher("Select * From Win32_PnPEntity");
ManagementObjectCollection objCollection = objSearcher.Get();
foreach (ManagementObject obj in objCollection)
{
string info = "HardwareID : "+obj["HardwareID"];
}
I expected the information of each RFID reader unique physical ID.
HardwareID is a string[] and not a string so to obtain is you have to do something like this
var objSearcher = new ManagementObjectSearcher("Select * From Win32_PnPEntity");
var objCollection = objSearcher.Get();
foreach (var queryObj in objSearcher.Get())
{
Console.WriteLine("Name {0}" , queryObj["Name"]);
if (queryObj["HardwareID"] == null)
Console.WriteLine("HardwareID: {0}", queryObj["HardwareID"]);
else
{
var arrHardwareID = (String[])(queryObj["HardwareID"]);
foreach (var arrValue in arrHardwareID)
{
Console.Write("HardwareID: {0}\t", arrValue);
}
}
}
Also, you can always use any NuGet package to ease your work like Kexla or ORMi

List only client computer objects in AD

I want to get all client-only computer objects from AD, I mean, Windows Clients machines. I am using the sample code from this thread, but I would like to know how I can filter servers out.
Here's my code:
class Program
{
public static List<string> GetComputers()
{
List<string> ComputerNames = new List<string>();
DirectoryEntry dirEntry = new DirectoryEntry("LDAP://neuventus.local");
DirectorySearcher mySearcher = new DirectorySearcher(dirEntry);
mySearcher.Filter = ("(objectClass=computer)");
mySearcher.SizeLimit = int.MaxValue;
mySearcher.PageSize = int.MaxValue;
foreach (SearchResult resEnt in mySearcher.FindAll())
{
string ComputerName = resEnt.GetDirectoryEntry().Name;
if (ComputerName.StartsWith("CN="))
ComputerName = ComputerName.Remove(0, "CN=".Length);
ComputerNames.Add(ComputerName);
}
mySearcher.Dispose();
dirEntry.Dispose();
return ComputerNames;
}
static void Main(string[] args)
{
List<string> newList = GetComputers();
newList.ForEach(Console.WriteLine);
System.IO.File.WriteAllLines("C:\\SavedLists.txt", newList);
}
}
Can anyone help me?
Try adding an operatingSystem condition to your filter.
mySearcher.Filter = "(&(objectClass=computer)(!(operatingSystem=*server*)))";
Note that this will only work if the all your servers are running a server operating system with server in the name. Also assume that no client machines run a server operating system.

How to retrieve the onboard ethernet MAC address of a computer?

I am trying to retrieve the MAC address for the onboard ethernet adapter from a computer, in order to generate a unique identifier for the device. Below is the approach I am using.
NetworkInterface[] ifConfig = NetworkInterface.GetAllNetworkInterfaces();
int maxHash = int.MinValue;
Guid D = Guid.Empty;
foreach (NetworkInterface net in ifConfig)
{
if (net.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
if (maxHash < net.GetPhysicalAddress().ToString().GetHashCode())
{
maxHash = net.GetPhysicalAddress().ToString().GetHashCode();
ID = new Guid(String.Concat("00000000-0000-0000-0000-", net.GetPhysicalAddress().ToString()));
}
}
}
However, the Bluetooth adapter, VM adapter and several other network adapters are also of the NetworkInterfaceType.Ethernet type. How can I specifically get the onboard ethernet connection's MAC address?
Doing a contains to omit those wouldn't be possible. Any help would be much appreciated.
I recently wrote a Powershell Script to generate a permanent system-format-immutable unique ID for a Windows PC for inventory purposes (QR encode the ID, print it on a sticker...).
It concatenates the PC manufacturer UUID field with the permanent MAC address of every PCI-connected network adapter (sorted alphabetically by MAC). The PCI requirement automatically dismisses removable or virtual NICs. The real script MD5-hashes the resulting string in order to obtain a more homogeneous identifier (constant length and 0-9A-F set of symbols), but I will omit this here for the sake of simplicity
I could’ve settled for the PC manufacturer UUID and call it a day, but I didn’t feel comfortable with an ID that relies on:
Each PC manufacturer in the world making the effort of filling in the UUID BIOS field.
Every PC manufacturer making the effort of keeping track of already used UUIDs
Basically, I tried to adhere to the intuitive idea of putting in the mixer as many non-removable components with permanent and “unique” (dream on) identifier as possible.
This ID generation technique is not fail proof: if a new PCI network adapter is added to the system, the ID will change. But with the popularization of integrated NICs I believe this is no longer something to worry about, if it ever was.
This solution is not directly applicable for C#, but I believe it can be easily adapted since Powershell shares almost the same .net object-class ecosystem.
#Variable names in spanish, but if I try to translate them in a hurry
#I will most certainly end up with a non-working script
$elpc=(Get-WmiObject -Class Win32_ComputerSystemProduct)
$id=$elpc.UUID #This is the UUID the manufacturer wrote somewhere in the BIOS
#Get network devices
#"Net" for network devices, "PCI*" because PCI connected devices begin that way
$dispositivosdered=#(Get-PnpDevice | Where-Object {($_.Class -eq "Net") -and ($_.InstanceId -like "PCI*")})
#Get network adapters
#Use "PermanentAddress" property. "MacAddress" property can be spoofed easily
$tarjetasdered=#(Get-Netadapter | Sort-Object PermanentAddress)
#Double loop to rule out any network adapters which are not PCI
#Comparison is made using long name, ie "Realtek PCIe GBE Family Controller #2"
#Is the only valid field I found to (inner) join the device and adapter worlds
for($j=0; $j -lt $tarjetasdered.length; $j++) {
for ($i=0; $i -lt $dispositivosdered.length; $i++) {
if($dispositivosdered[$i].FriendlyName -eq $tarjetasdered[$j].InterfaceDescription) {
if(-not [string]::IsNullOrEmpty($tarjetasdered[$j].PermanentAddress)) {
$id= $id + $tarjetasdered[$j].PermanentAddress.Replace("-", "");
}
}
}
}
As an option (not the best, but still =) ) - You can try to use
metric. In most cases the metric of the network to a physical network
card priority
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
ManagementObjectSearcher query = new
ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
if (!(mo["Description"].ToString().Contains("VM")))
{
if (!(mo["Description"].ToString().Contains("Virtual")))
{
if (!(mo["Description"].ToString().Contains("Hyper")))
{
string[] addresses = (string[])mo["IPAddress"];
string IPConnectionMetric = Convert.ToString(mo["IPConnectionMetric"]).Trim();
foreach (string ipaddress in addresses)
{
listBox1.Items.Add(ipaddress + ";" + IPConnectionMetric);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.Items.Count > 1)
{
int maximum = int.MinValue;
int minimum = int.MaxValue;
for (int i = 0; i < listBox1.Items.Count; i++)
{
int output = Convert.ToInt32(listBox1.Items[i].ToString().Split(';')[1]);
if ((int)output > maximum)
maximum = (int)output;
}
for (int i = 0; i < listBox1.Items.Count; i++)
{
int output = Convert.ToInt32(listBox1.Items[i].ToString().Split(';')[1]);
if ((int)output < maximum)
minimum = (int)output;
if (listBox1.Items[i].ToString().Contains(minimum.ToString()))
{
var minmetric = listBox1.Items[i].ToString();
NetworkInterface[] ifConfig = NetworkInterface.GetAllNetworkInterfaces();
int maxHash = int.MinValue;
Guid D = Guid.Empty;
foreach (NetworkInterface net in ifConfig)
{
if (net.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
if (maxHash < net.GetPhysicalAddress().ToString().GetHashCode())
{
maxHash = net.GetPhysicalAddress().ToString().GetHashCode();
foreach (UnicastIPAddressInformation ip in net.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (ip.Address.ToString().Contains(minmetric.ToString().Split(';')[0]))
{
var ID = new Guid(String.Concat("00000000-0000-0000-0000-", net.GetPhysicalAddress().ToString()));
}
}
else
{
NetworkInterface[] ifConfig = NetworkInterface.GetAllNetworkInterfaces();
int maxHash = int.MinValue;
Guid D = Guid.Empty;
foreach (NetworkInterface net in ifConfig)
{
if (net.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
if (maxHash < net.GetPhysicalAddress().ToString().GetHashCode())
{
maxHash = net.GetPhysicalAddress().ToString().GetHashCode();
var ID = new Guid(String.Concat("00000000-0000-0000-0000-", net.GetPhysicalAddress().ToString()));
}
}
}
using system.Management;
private string GetMACAddress()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
string MACAddress = String.Empty;
foreach (ManagementObject mo in moc)
{
if (MACAddress == String.Empty) // only return MAC Address from first card
{
if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
}
mo.Dispose();
}
MACAddress = MACAddress.Replace(":", "");
return MACAddress;
}

Identify connected network printers by its IP address

I want to list up all printers connected to my network (including not installed)
I could manage to get all IP addresses of connected devices to my PC, by ping to all the addresses on gateway. And then I obtained Host name by
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
return entry.HostName;
I noticed that printers does not have a Host name.
Now I need to figure out which IP's belongs to a printer of my IP list or mac address.
how can i do that.
When we install a network printer, Windows is listing the names of printers. Can we obtain the such name using IP or MAC?
Include System.Management with
using System.Management;
foreach (string printername in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printername);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
try
{
foreach (ManagementObject printer in coll)
{
foreach (PropertyData property in printer.Properties)
{
Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
}
}
}
catch (ManagementException ex)
{
Console.WriteLine(ex.Message);
}
}
}
And you will get all the info of every printer, including name and IP
If you want to get the printer IP from the name just use
If(printer.Properties.Caption.Contains("Printer name")
{
return printer.Properties.PortName;
}
Otherwise, to obtain the ip from the name, reverse the process and search for the ip and return the name.
For printers in the network, try this:
using System.Management;
private void Form1_Load(object sender, EventArgs e)
{
System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer");
System.Management.ManagementObjectSearcher mosearcher = new
System.Management.ManagementObjectSearcher(oquery);
System.Management.ManagementObjectCollection moc =
mosearcher.Get();
foreach (ManagementObject mo in moc)
{
System.Management.PropertyDataCollection pdc = mo.Properties;
foreach (System.Management.PropertyData pd in pdc)
{
if ((bool)mo["Network"])
{
MessageBox.Show(String.Format("{1}", mo[pd.Name]));
}
}
}
}
// To list printers installed on computer online/offline
Code Snippet
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
MessageBox.Show(printer);
}

Categories