Cannot find all connected devices to my LAN - c#

I am creating a UWP application, and I am trying to find all devices connected to my LAN at home. I have a pi running windows iot that is a controller and I have another application running on my computer currently but will be running on another device later. What I need to do is find what address all pi's are and allow the user to select the one they want. I have started by just finding all things connected to my local network.
List<string> connectedDevices = new List<string>();
foreach (HostName localHostName in NetworkInformation.GetHostNames())
{
if (localHostName.IPInformation != null)
{
if (localHostName.Type == HostNameType.Ipv4)
{
connectedDevices.Add(localHostName.ToString());
}
}
}
ConnectedDevices = connectedDevices;
This code will return some ip addresses but not the one the pi is connected to. I have verified that the pi is in fact connected by pining it and also I am able to control it when entering the ip address in my application myself.
What I am trying to accomplish is taking the master device with the display and finding the slave devices on the local network so multiple slaves can be added and if an ip address of a slave has changed it will be updated so my app can still call it.
Any help would be appreciated.

Related

Windows UWP Bluetooh multiple devices showing for single device

I am currently working on a C#-UWP app that needs to be able to discovery bluetooth devices (Not BLE) on the network and ones that have been previously connected to/paired.
Im sure anyone who is new to this task will have quickly found the documentation and example are of little help. I have learned more from Stackoverflow questions about peoples experimentations than from the docs and examples, but anyways.
My main question/problem is this: After setting up the device watcher to find bluetooth devices I found that I consistently get multiple additions of the same device but having a different bluetooth address (this is a device that was previously paired but not live on the network). After much investigate and brainstorming, we discovered that each device id is actually a pairing of the devices MAC address and the BT receivers MAC address.
The reason I was getting 3 device additions per 1 physical device is because I have connected to that same device with 3 different BT receiver dongles in the past. So my question is, is there anyway to make the device watcher return the device that corresponds to the currently active BT receiver dongle?
Otherwise I will need to find the currently active BT receivers MAC address and filter out the devices that do not have this, because otherwise the user will see 3 identical devices to select and only 1 of them will pass while the other 2 will fail.
While on this subject I would also like to mention that the device properties dont seem to be working. Before creating the watcher, I have a list of properties like this for example:
requestedProperties.Add("System.Devices.Aep.DeviceAddress");
requestedProperties.Add("System.Devices.Aep.IsConnected");
requestedProperties.Add("System.Devices.Aep.Bluetooth.Le.IsConnectable");
requestedProperties.Add("System.Devices.Aep.IsPresent");
requestedProperties.Add("System.Devices.Aep.ContainerId");
requestedProperties.Add("System.Devices.Aep.ModelId");
requestedProperties.Add("System.Devices.Aep.Manufacturer");
requestedProperties.Add("System.Devices.Aep.ProtocolId");
requestedProperties.Add("System.Devices.Aep.SignalStrength");
But when I debug the device that is added, it doesnt have any properties:
debug info showing no properties for added device
I would be useful to have this information.
Thank you for any input or suggestions.
Update
I found a quick solution that overcomes this problem (although i did find a lot more problems with the device watcher but that is probably a topic for another question).
For now I simply get the current BT adaptors MAC address and then check each incoming device if it has this MAC address in its pair. If it does not that means the device is paired with an old/unused BT adaptor.
/* NOTE:
Windows allows only 1 BT adapter to be active on 1 machine at a time
Therefore this function will either return the active dongle or a null if
there is no BT adapter on the machine or its disabled.
*/
BluetoothAdapter BTAdaptor = await BluetoothAdapter.GetDefaultAsync();
if (BTAdaptor == null)
{
// Log error
// return
}
//
// Code block to check if the BT adaptor can support the BT tech stack you are interested in.
//
// Format into hex with 12 characters (12 being the number of characters for MAC address)
string tempMac = BTAdaptor.BluetoothAddress.ToString("X12").ToLower();
// Pattern for MAC address.
string pattern = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})";
string replace = "$1:$2:$3:$4:$5:$6";
m_strBTAdapterMAC = Regex.Replace(tempMac, pattern, replace);
Then when the device is added/updated/removed by the watcher event, check it:
// If device is not paired with the currently used BT adapter.
if (deviceInfo.Id.Contains(m_strBTAdapterMAC) == false)
{
// Device paired with old dongle, dont want to show the user.
return;
}
If anyone ever figures out how to make the device watcher just not give old devices, please let me know, its probably a better solution.

Mac Id is coming same in 2 PCs while using C#

I have developed a software in C#, in which registration is done using mac id of PC as unique identifier. I registered the software on one PC using internet via usb tethering of my mobile, it took a mac id and got registered successfully. But when I tried to register on another PC using my mobile's internet via usb tethering, it is showing the same mac id which I got on registering first PC. I checked mac id of both PCs using ipconfig/all command in cmd and there same id is shown under physical address when my mobile is connected for internet. Why is this happening? What is the solution for this?
Code I used to fetch mac id:
string macAddresses = "", FinalmacAddresses = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
macAddresses = nic.GetPhysicalAddress().ToString();
break;
}
FinalmacAddresses = macAddresses.Trim().ToString();
return FinalmacAddresses;
First thing is, you should never use a mac address as a unique identifier. There are tools and even simple ways by which you can assign multiple devices with the same mac address (Mac address spoofing). That is also not good, if we look through the security perspective.
I would recommend using a GUID instead.

How to access two different services from the same ble device

For example, I have two heart rate monitors paired with my tablet PC.
I'm using such code to get list of HRM devices:
var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync
(
GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate)
);
Then I show a listbox in GUI with device names got from devices[i].Name.
For example, I select device with index 0. Then I can get access to it HR serivice and HRM characteristic:
var service = await GattDeviceService.FromIdAsync(devices[0].Id);
var characteristic = await service.GetCharacteristics(attCharacteristicUuids.HeartRateMeasurement);
Along with heart rate I need a battery status. How can I get access to battery service of the same (already selected) device?
Some information before we start:
You do have to pair your Bluetooth devices with your computer, before you could scan them!
Listing your paired devices:
ListBox1.Items.Clear();
var devices = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
foreach (var device in devices)
{
ListBox1.Items.Add(device);
}
If you want to know the battery life of the Bluetooth device:
How to get the battery level after connect to the BLE device?
To access multiple services at once, you need to "reconnect" to the device:
Device A can connect only one at a time to service S on Device B. Device A can connect to service S on Device B, C, D and E, etc at the same time.
#alanjmcf
Source: Establishing multiple bluetooth SPPs at the same time
But do not get confused with the method GetAllIncludedServices();, because it does really return "included services". As one answer stated at an other question:
You probably don't want to get the "included services". Included services is a special concept in BLE which I doubt you are using that is used to link one service from another.
#Emil

Obtaining the IP and MAC of client machines connecting to my ASP.NET MVC application on a server

I have just signed up because I need some clarification. I am an old man but a new graduate of a Systems Analysis college program and am on my first "real" job designing a system for a local company. Here is the deal. I am using ASP.NET MVC. Now, the company has assembly lines in a large manufacturing plant. Along the lines are stations where workers do a specific job on the line. The company has paper instructions that explain to the worker step by step how to do the job at their station. They want all this done electronically now....this is what I 'm doing.
So, when the leader of the assembly line starts their shift, they log into the system by opening up IE and connecting to the application server. From there, the leader picks a part to "make" on the line. The system then goes into the repository of instruction documents and retrieves all the documents needed by each station on the line to run the selected part. The system then needs to prepare the documents according to the station that will use them (ie. station 1 docs, station 2 docs,....etc). Then, the system needs to automatically open up the IE browser window on the client machine at each station on the line and display the login screen. The worker then logs onto the station and is presented with the "dashboard" screen with the instruction forms right there in front of him with buttons to navigate through the various docs for his station.
So now, we are wanting to have the system store the IP and Mac addresses of each station machine along each assembly line in a table along with fields that denote the assembly line and station # (ie. so a row in the table would have MAC | IP | ASSEMBLYLINE-ID | STATION-ID). This table will be populated before hand by admins so that the system knows already what the Mac and IP are for each machine on the floor. So, when the leader picks a part to run, the system can just check the machine the leader is logged into and get its MAC and IP and then look up in the table what line the machine is on. Then it can create a document queue for each station on the line, and then when the queues are ready, it can look in the table for the IP's of each machine on the line so that it can open the log on screen on the right machines.
However, it is possible that IP's may change from time to time. For this reason, we want to make sure we also use MAC addresses to validate the identity of a station machine whenever any communication needs to happen between the system and the clients. IP's alone just aren't good enough. Further, we are using all zero clients for this on the stations.
So, if you're still reading, lol. How can my system on the server, run a getMAC command on a machine that connects to it?
A web server cannot get the MAC address of a client machine. MAC addresses are stored on the physical ethernet layer and are not routed through socket connections. A MAC address stored in a packet is changed on every hop of a packet's journey. MAC is an abbreviation for Media Access Control, with "Media" referring to the local communication media. While source and destination IP-Addresses remain the same throughout the journey (and are used for long-distance routing decisions), the source and destination MAC-Addresses just indicate the next hop.
That being said, you can get the IP address like so:
Request.UserHostAddress()
However, as you yourself pointed out, this isn't reliable. Especially if the computers are behind a proxy or firewall.
To address your real problem, which is identifying a machine in your assembly line, one method is to get the computer name. You can open a command window and type the command hostname and that will return the computer name. It should be unique for each of your machines. If not, you can set it by right clicking on Computer. To get this name through javascript, use this code:
function GetComputerName()
{
try
{
var network = new ActiveXObject('WScript.Network');
var computerName = network.computerName;
return computerName;
}
catch (e) { }
return "";
}
Note that this code will only with with Internet Explorer and it may require you to enable special security settings inside the browser.

32Feet.Net connecting to Bluetooth speakers

So I am trying to connect a bluetooth speakers from a script. I am using 32feet.net and I have successfully found the device but it doesn't work when I try to pair and connect to it.
This is the code im using to pair to device, this always fails not sure why:
private static void connected(BluetoothDeviceInfo[] dev)
{
// dev[foundIndex];
bool paired=false;
paired = BluetoothSecurity.PairRequest(dev[foundIndex].DeviceAddress, "1166");
if (paired)
Console.WriteLine("Passed, Device is connected.");
else
Console.WriteLine("Failed....");
}
Here is the code called after connected to actually connect to the device: bc is my bluetooth client var.
bc.BeginConnect(devInfo[foundIndex].DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), devInfo[foundIndex]);
private static void Connect(IAsyncResult result)
{
if (result.IsCompleted)
{
Console.Write("Connected... ");
}
}
Any help would be appreciated. I am new to 32feet.net so i dont know much about this, i tried following code online to get where im at.
Try BluetoothDeviceInfo.SetServiceState. That will ask Windows to connect to the audio service on the device -- hopefully that'll do the job.
See https://32feet.codeplex.com/wikipage?title=Connecting%20to%20Bluetooth%20Services
Sometimes we don’t want our application to itself send data to/from a remote service but we want instead the local operating system to do so. This is the case for keyboard/mouse/etc with HID, networking with DUN/NAP/PAN/etc, Headset/Handsfree etc.
and then
The short answer in this case is to use BluetoothDeviceInfo.SetServiceState. This is the API equivalent to manually checking the respective checkbox on the “Services” tab of the Device dialog in Bluetooth Control panel.
Also, in these days of Secure Simple Pairing, using PairRequest is fine only if all peer devices will use old style PIN code authentication, otherwise instantiate a BluetoothWin32Authentication and then do the connect (here indirectly via SetServiceState) and handle the authentication in the authentication callback.

Categories

Resources