I am trying to connect to a printer(by MAC address) and print. I am encountering several issues that I tried to overcome for hours with no success. I tried several different Methods:
Method 1: Using PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{00001101-0000-1000-8000-00805F9B34FB}" works on first attempt to connect. When I try to reopen the connection after closing connection, it was not able to find any paired devices. When I exit application and rerun, I get the following exception: "Element not found. (Exception from HRRESULT:0x80070490) at socket.ConnectAsync()
//Search for devices based on service
PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{00001101-0000-1000-8000-00805F9B34FB}";
//bluetooth device to connect to
var m_bluetoothDevice;
//paired bluetooth device list
var m_pairedDevices = await PeerFinder.FindAllPeersAsync();
if (m_pairedDevices.Count > 0)
{
foreach (PeerInformation device in m_pairedDevices)
{
//Find the device with matching bluetooth mac address (eg. "00:AA:BB:CC:DD:EE")
String macAddr = device.HostName.RawName;
if (macAddr.Contains(m_bluetoothAddress.ToUpper()))
{
m_bluetoothDevice = device;
break;
}
}
}
//Device not paired
if (m_bluetoothDevice == null)
throw new Exception("Device was not paired with system.");
StreamSocket socket = new StreamSocket();
if (socket != null)
{
//Connect to device. Run this task synchronously
IAsyncAction taskConnect = socket.ConnectAsync(m_bluetoothDevice.HostName, m_bluetoothDevice.ServiceName);
taskConnect.AsTask().Wait();
if (taskConnect.ErrorCode != null)
{
throw (taskConnect.ErrorCode);
}
}
Method 2: Using PeerFinder.Alternative["Bluetooth:Paired" = "", I am able to connect once. After closing connection and reopening connection, I get the following Exception "Element not found. (Exception from HRRESULT:0x80070490) at socket.ConnectAsync().
//Search for devices based on service
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
//bluetooth device to connect to
var m_bluetoothDevice;
//paired bluetooth device list
var m_pairedDevices = await PeerFinder.FindAllPeersAsync();
if (m_pairedDevices.Count > 0)
{
foreach (PeerInformation device in m_pairedDevices)
{
//Find the device with matching bluetooth mac address (eg. "00:AA:BB:CC:DD:EE")
String macAddr = device.HostName.RawName;
if (macAddr.Contains(m_bluetoothAddress.ToUpper()))
{
m_bluetoothDevice = device;
break;
}
}
}
//Device not paired
if (m_bluetoothDevice == null)
throw new Exception("Device was not paired with system.");
StreamSocket socket = new StreamSocket();
if (socket != null)
{
//Connect to device. Run this task synchronously
IAsyncAction taskConnect = socket.ConnectAsync(m_bluetoothDevice.HostName, "{00001101-0000-1000-8000-00805F9B34FB}");
taskConnect.AsTask().Wait();
if (taskConnect.ErrorCode != null)
{
throw (taskConnect.ErrorCode);
}
}
Anyone experiencing the same issue? What am I doing wrong?
Thanks in advance
Related
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.
I have an application (C#) where I try to get the IP of a device based on its HostName and I do it as follows:
public static IPAddress[] GetIPsByName(string hostName)
{
try
{
// Check if the hostname is already an IPAddress
IPAddress outIpAddress;
if (IPAddress.TryParse(hostName, out outIpAddress) == true) return new IPAddress[] { outIpAddress };
IPAddress[] addresslist = Dns.GetHostAddresses(hostName);
if (addresslist == null || addresslist.Length == 0) return new IPAddress[0];
return addresslist.Where(o => o.AddressFamily == AddressFamily.InterNetwork).ToArray();
}
catch (ArgumentNullException arNull)
{
return new IPAddress[0];
}
catch(ArgumentOutOfRangeException arOut)
{
return new IPAddress[0];
}
catch(SocketException socEx)
{
return new IPAddress[0];
}
catch(ArgumentException arExp)
{
return new IPAddress[0];
}
catch (Exception ex)
{
return new IPAddress[0];
}
}
For some HostNames its IP is obtained correctly, but for others the SocketException exception occurs where the error is (SocketErrorCode = HostNotFound). (Occurs by executing the line Dns.GetHostAddresses (hostName);)
This problem would be normal if the device was disconnected from the network, but when performing a search with an IP scanner, the device is connected to the network (It shows its Hostname, its IP and its MAC address)
Any suggestions of what may be going on?
im using huawei e359
Hello im creating a simple program. where my code will connect the 3g modem to the internet. because a part of my program need to access the internet.
i did some search how to do this using c#
this is my code for adding entry
string deviceName = null;
path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
using (RasPhoneBook pbk = new RasPhoneBook())
{
pbk.Open(path);
foreach (var item in RasDevice.GetDevices())
{
if (item.DeviceType.ToString().ToLower() == "modem")
{
deviceName = item.Name;
}
}
RasDevice device = RasDevice.GetDevices().Where(o => o.Name == deviceName && o.DeviceType == RasDeviceType.Modem).First();
if (!RasEntry.Exists("Your Entry", path))
{
RasEntry entry = RasEntry.CreateDialUpEntry("Your Entry", "+00000000000", device);
pbk.Entries.Add(entry);
}
}
and this is the code for dialing the device
using (RasDialer dialer = new RasDialer())
{
dialer.EntryName = "Your Entry";
dialer.PhoneBookPath = path;
dialer.AllowUseStoredCredentials = true;
dialer.Dial();
}
this is the error, it prompts when i dial the device
The remote computer did not respond. To make sure that the server can be reached, ping the remote computer.
I am using the latest version of pcap.net to capture network traffic on my local pc ethernet card. I am using the following code to capture all traffic associated with a specific mac address.
private void bwCapture_DoWork(object sender, DoWorkEventArgs e)
{
capture = true;
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
if (allDevices.Count == 0)
{
MessageBox.Show("No interfaces found!");
return;
}
if (capture)
{
// Print the list
for (int i = 0; i != allDevices.Count; ++i)
{
LivePacketDevice device = allDevices[i];
this.BeginInvoke((Action)delegate () { cmbNetworkDevice.Items.Add((i + 1) + ". " + device.Name); });
}
// Take the selected adapter
PacketDevice selectedDevice = allDevices[deviceSelected];
// Open the device
using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture
PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
50)) // read timeout
{
this.BeginInvoke((Action)delegate () { rtbCaptured.Text = "Listening on " + selectedDevice.Description + Environment.NewLine; });
// Retrieve the packets
Packet packet;
while (capture)
{
try
{
BerkeleyPacketFilter filter = communicator.CreateFilter("ether host <<MAC ADDRESS>> and tcp port 2000");
communicator.SetFilter(filter);
PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
switch (result)
{
case PacketCommunicatorReceiveResult.Timeout:
// Timeout elapsed
continue;
case PacketCommunicatorReceiveResult.Ok:
this.BeginInvoke((Action)delegate ()
{
IpV4Datagram ip = packet.Ethernet.IpV4;
TcpDatagram tcp = ip.Tcp;
if (tcp != null && ip != null)
{
string IPCheck = ip.Source.ToString();
int PortCheck = tcp.DestinationPort;
dgvIncomingPackets.Rows.Add(packet.Timestamp.ToString("MM-dd-yyyy hh:mm:ss"), packet.Length, tcp.SequenceNumber , ip.IpV4.Protocol, ip.Source, tcp.SourcePort, ip.Destination, tcp.DestinationPort);
rtbPacketDeconstruct.Text = WordWrap(ProcessString(packet.BytesSequenceToHexadecimalString()),47);
string convertThis = ProcessString(packet.BytesSequenceToHexadecimalString());
dgvIncomingPackets.FirstDisplayedScrollingRowIndex = dgvIncomingPackets.RowCount - 1;
}
else
{
rtbCaptured.Text += "Error : TCP Null Value" + Environment.NewLine;
}
});
break;
default:
throw new InvalidOperationException("The result " + result + " should never be reached here");
}
}
catch (Exception ex)
{
this.BeginInvoke((Action)delegate ()
{ rtbCaptured.Text += "Exception : " + ex; });
}
}
}
}
}
The code above works however it is not detecting all of the skinny events. When viewing the network traffic with WireShark I am able to see the condition changes in a Cisco 7960 IP Phone including off hook, lamp messages, displaynotification messages.
While these packets are registered in Wireshark on my PC they appear not to be captured using the code above.
My understanding is that skinny uses tcp ports 2000 and 49828 for communication between CUCM and the device. My code does see the TCP ACK and WHOAMI packets.The MAC address being monitored in the Cisco IP Phone. My PC is connected to this device through the built in hub on the device(This isn't the issue because WireShark is showing the events on my PC where my code is not)
What am I missing here. I am a novice to programming and learning on the fly here. (As such I am aware my code isn't the cleanest or well written)
Thanks,
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