c#: Dial a modem using dotras - c#

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.

Related

How we can change USB settings of connected device through c#

I am working on an application where I am placing the json files at particular directory in connected android device. Android device has an application which used to read the data from json files and then files are deleted. I am using MediaDevices library to list and connect devices in WPF application.
public Form1()
{
InitializeComponent();
bindDevices();
}
private void bindDevices()
{
try
{
devices = MediaDevice.GetDevices();
var test = devices.Select(x => x).ToList();
List<deviceDetails> deviceNames = (from d in test
select new deviceDetails
{
deviceID = d.DeviceId,
deviceName = d.FriendlyName == "" ? d.Description : d.FriendlyName
}).ToList();
foreach (MediaDevice device in devices)
{
device.Connect();
lblBattery.Text = device.PowerLevel.ToString();
try
{
getDirectory(device);
}
catch (Exception ex)
{
}
finally
{
device.Disconnect();
}
}
comboBox1.ValueMember = "deviceID";
comboBox1.DisplayMember = "deviceName";
comboBox1.DataSource = deviceNames;
//var device = devices.FirstOrDefault().FriendlyName == "" ? devices.FirstOrDefault().Description : devices.FirstOrDefault().FriendlyName;
//label2.Text = device;
}
catch (Exception ex)
{
MessageBox.Show("Error : -" + ex.Message);
label2.Text = "Can not connect to device";
}
}
Above mentioned steps are working fine.
Problem: Sometimes, while device is connected through USB, if I check on file explorer at PC, it shows me json files but if I check in android device files were removed. If, I am trying to delete those files through PC then it show message files are locked. Once, I disconnect/connect the device again then files are removed from device directory.
How, I can reset the connectivity of device so connection will be reset through code.

Disconnecting VPN in C# using DOTRAS

I'm making a VPN connection using DOTRAS in C# by the click of a button, using the following method.
string VpnName = "Test1";
string Destination = "191.20.0.21";
string PresharedKey = "myKey";
RasPhoneBook PhoneBook = new RasPhoneBook();
PhoneBook.Open();
RasEntry VpnEntry = RasEntry.CreateVpnEntry(VpnName, Destination, DotRas.RasVpnStrategy.L2tpOnly, DotRas.RasDevice.Create(VpnName, DotRas.RasDeviceType.Vpn));
VpnEntry.Options.UsePreSharedKey = true;
VpnEntry.Options.UseLogOnCredentials = true;
VpnEntry.Options.RequirePap = true;
VpnEntry.Options.RequireMSChap = false;
VpnEntry.Options.RequireMSChap2 = false;
PhoneBook.Entries.Add(VpnEntry);
VpnEntry.UpdateCredentials(RasPreSharedKey.Client, PresharedKey);
Console.WriteLine("VPN connected successfully");
The VPN connects successfully.
I need to disconnect it now (Something other than simply removing it).
How will that be possible?
here:
var conn = RasConnection.GetActiveConnections().Where(c => c.EntryName == "Test1").FirstOrDefault();
if (conn!=null)
{
conn.HangUp();
}

Issue viewing all skinny traffic using pcap.net in a C# Winform application

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,

How to get connected web site ip adress from browser?

im trying to detect which website user connected to..
I tried to get tcp connections and i parsed them for example i tried to detect facebook. But when i logout and close facebook its still displaying 31.13.93.3 (ip of facebook)
Here is my codes..
public partial class Form1 : Form
{
static string faceIP = "31.13.93.3";
static string _targetIP,_targetPORT,_connectedWebSiteIP,_connectedWebSitePORT = string.Empty;
static string[] splitted = null;
public Form1()
{
/* 127.0.0.1:5037:127.0.0.1:49569
* First = 127.0.0.1
* Second = 5037
* Third = 127.0.01
* Fourth = 49569
*/
InitializeComponent();
this.Name = "Active Tcp Connections";
if (findFacebookIP())
{
MessageBox.Show("You opened or connected to facebook page!");
}
}
public static bool findFacebookIP(){
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
foreach (TcpConnectionInformation c in connections)
{
string tcpCon = string.Format("{0}:{1}", c.LocalEndPoint.ToString(), c.RemoteEndPoint.ToString());
splitted = tcpCon.Split(':');
_targetIP = splitted[0]; // Main Machine ip adress / local ip address (First)
_targetPORT = splitted[1]; // Main machine port number (Second)
_connectedWebSiteIP = splitted[2]; // (Third)
_connectedWebSitePORT = splitted[3]; // (Fourth)
if (_connectedWebSiteIP == faceIP)
{
return true;
}
}
return false;
}
// face ip = 31.13.93.3
}
Also im need to run it background all time beacuse this method is working for just opening.. you can see i wrote it in Form1() constructor method.
Thank you for your help.
Check using TcpState:
foreach (TcpConnectionInformation c in connections)
{
//------------rest of your code
if(c.State == TcpState.Closed)
return false;
//------------rest of your code
}
And for running in background use BackgroundWorker.

FindAllPeersAsync() and StreamSocket.ConnectAsync() issue

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

Categories

Resources