The main question is: could c# application track moment when user starts to upload file from his local machine to internet? It might be any process on machine. Tracking application does not triggered uploading file process.
There is example of code that captures so much outgoing TCP and UDP traffic. But I need to filter only packets contain file transferring data.
public static void Start()
{
//get ip address
IPAddress[] addrList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
string IP = addrList[0].ToString();
//var devices = SharpPcap.WinPcap.WinPcapDeviceList.Instance;
var devices = CaptureDeviceList.Instance;
// differentiate based upon types
int count = devices.Count;
if (count < 1)
{
Console.WriteLine("No device found on this machine");
return;
}
for (int i = 0; i < count; ++i)
{
// CaptureFlowReceive(IP, i);
CaptureFlowSend(IP,i);
}
while (true)
{
//Call refresh function every 1s
RefershInfo();
}
}
private static void CaptureFlowSend(string IP, int deviceID)
{
ICaptureDevice device = CaptureDeviceList.New()[deviceID];
device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalSend);
int readTimeoutMilliseconds = 1000;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
string filter = "src host " + IP + " and ip ";
device.Filter = filter;
device.StartCapture();
}
private static void device_OnPacketArrivalSend(object sender, CaptureEventArgs e)
{
var rawCapture = e.Packet;
var packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
var data = packet.PayloadPacket.PayloadPacket.PayloadData;
}
public static void RefershInfo()
{
Thread.Sleep(1000);
}
It seems I have found solution.
With netstat -a -n -o command we could receive all processes that uses tcp and udp sockets. Also we could get DiskUsage info by process from process list received in previous step. Certainly it is not perfect solution but it is almost closely that I need.
Related
I am currently creating a C# network scanner, but I have run into an issue where I am not able to detect devices other than the one running the code. I have been following a couple guides as to how to go about it, but even if I just copy and paste their code it runs into the same issue. I have a feeling it might be due to firewalls because of this but if that is the case how would I do that?
This is my boiled down code using just console. It runs through all the IPs, while rather slow, and picks up this device but not the others I have connected. It uses the prebuilt ping class and sends it to every possible device on the subnet.
static void Main(string[] args)
{
Ping myPing;
PingReply reply;
IPAddress address;
IPHostEntry host;
string iP = "172.20.10.";
Console.WriteLine("start loop");
for (int i = 2; i < 240; i++)
{
Console.WriteLine("Hello");
string deviceIP = iP + i.ToString();
Console.WriteLine("selected " + deviceIP);
myPing = new Ping();
reply = myPing.Send(deviceIP);
Console.WriteLine("contacting " + deviceIP);
if (reply.Status == IPStatus.Success)
{
host = Dns.GetHostEntry(deviceIP);
Console.WriteLine(host.HostName.ToString() + " is connected");
}
else
{
Console.WriteLine("^non existant^");
}
}
Console.WriteLine("end loop");
}
I Have created some code for communicating with a device over the serialport. By sending certain command with serialPort1.WriteLine I should receive answer with serialPort1.ReadExisting(). Well I'm able to detect the device but I need to read some other information but to get this information correct I only get it when I place the code in a button_Click function. The funny thing is that All is written in a function and I wish to get the information after the device is detected immediately. When I call the function after the device has been detected it doesn't work and when I call the function after the button is pressed I get the correct information. I do not understand why this is so.
The function for detecting the device is like this:
private void detectVM25ToolStripMenuItem_Click(object sender, EventArgs e)
{
// Detect VM25 and show connection is established
String device;
//Search all portnames
String[] ports = SerialPort.GetPortNames();
int totalPorts = ports.Length;
int count = 0 ;
//Test which enabled port is the VM25.
foreach (string port in ports)
{
count = count + 1;
serialPort1.PortName = port;
serialPort1.Open();
if (serialPort1.IsOpen)
{
serialPort1.WriteLine("#S" + Environment.NewLine);
answer = serialPort1.ReadExisting();
if (answer != "")
{
device = answer.Substring(0, 4);
if (device == "VM25")
{
getRecordings();
statusLblDevice.ForeColor = Color.LawnGreen;
statusLblDevice.Text = port + " - " + device + " - Connected";
VM25Port = port;
}
}
else if (answer == "")
{
serialPort1.Close();
if (count == totalPorts)
{
MessageBox.Show("No device found");
}
}
}
}
}
The function getRecordings() should give me data. If I place this function in my form and get called after a button is pressed I get the correct info but when it is inside the above function it doesn't do anything.
private void getRecordings()
{
if (serialPort1.IsOpen)
{
serialPort1.WriteLine("#H" + Environment.NewLine);
memoryInfo = serialPort1.ReadExisting();
label1.Text = memoryInfo;
}
}
Does anybody knows why this is the case? I would like not to have press a button and get this information after it has detected the device. I also tried to create a delay with `Task.Delay()' unfortunately this did not help
It's surely because you have no synchronization whatsoever. .ReadExisting() does not get an entire response, it gets only what's already been received. So calling it right after .WriteLine(...)... well your data hasn't even reached the device yet, so there definitely won't be an answer ready to read.
Since you know the length of your expected answer (or at least the prefix you're interested in), set the read timeout and then call .Read() (or better, .BaseStream.ReadAsync()) with that length.
Even that is only going to mostly work when the port is freshly opened... for subsequent commands you risk getting data in your buffer from the tail end of a reply to an earlier command. Correct use of a serial port really requires the two ends to agree on some sort of framing, whether that is "a message contains only ASCII and ends with CR+LF" or "a message starts with the length of its payload" or some less common scheme.
with the point out of #Ben Voigt I discovered I should tackle this issue different.
I have use the method serialPort1.ReadTo() because I know that each message end with "/a".
therefore I fixed the function as follows
private void detectVM25ToolStripMenuItem_Click(object sender, EventArgs e)
{
// Detect VM25 and show connection is established
String device;
//Search all portnames
String[] ports = SerialPort.GetPortNames();
int totalPorts = ports.Length;
int count = 0 ;
//Test which enabled port is the VM25.
foreach (string port in ports)
{
count = count + 1;
serialPort1.PortName = port;
serialPort1.Open();
if (serialPort1.IsOpen)
{
serialPort1.WriteLine("#S" + Environment.NewLine);
answer = serialPort1.ReadExisting();
if (answer != "")
{
device = answer.Substring(0, 4);
if (device == "VM25")
{
statusLblDevice.ForeColor = Color.LawnGreen;
statusLblDevice.Text = port + " - " + device + " - Connected";
VM25Port = port;
serialPort1.WriteLine("#H" + Environment.NewLine);
string input = serialPort1.ReadTo("/a");
label1.Text = input;
string totalMeasurements = input.Substring(0, 11);
string totalFFT = input.Substring(11, 11);
statusLblMeas.Text = totalMeasurements;
statusLblFFT.Text = totalFFT;
}
}
else if (answer == "")
{
serialPort1.Close();
if (count == totalPorts)
{
MessageBox.Show("No device found");
}
}
}
}
}
Note the changes of reading the serialport where I stated that it should read up to "/a"
I have an issue about the server-client communication.
I googled around but I did not find a solution to this.
Right now I am using 32feet in order to get in touch 2 or more (till 7) BT clients to 1 BT server.
I need to broadcast a message from the server to every device in the same time, but I don't know how to do it.
The only way I figured out was to use the list of connection in order to send the message one per time, but it means a delay between each message sent (around 100 ms per device). Unfortunately it means to have a large delay on the last one.
Can someone please give me an advice on how to solve this problem?
Is there a way to broadcast the message to all devices in the same time?
If it can be helpfull, here there is the handle of connection and reading from devices.
Thanks for your help
private void btnStartServer_Click(object sender, EventArgs e)
{
btnStartClient.Enabled = false;
ConnectAsServer();
}
private void ConnectAsServer()
{
connessioniServer = new List<BluetoothClient>();
// thread handshake
Thread bluetoothConnectionControlThread = new Thread(new ThreadStart(ServerControlThread));
bluetoothConnectionControlThread.IsBackground = true;
bluetoothConnectionControlThread.Start();
// thread connessione
Thread bluetoothServerThread = new Thread(new ThreadStart(ServerConnectThread));
bluetoothServerThread.IsBackground = true;
bluetoothServerThread.Start();
}
private void ServerControlThread()
{
while (true)
{
foreach (BluetoothClient cc in connessioniServer)
{
if (!cc.Connected)
{
connessioniServer.Remove(cc);
break;
}
}
updateConnList();
Thread.Sleep(0);
}
}
Guid mUUID = new Guid("fc5ffc49-00e3-4c8b-9cf1-6b72aad1001a");
private void ServerConnectThread()
{
updateUI("server started");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
while (true)
{
BluetoothClient conn = blueListener.AcceptBluetoothClient();
connessioniServer.Add(conn);
Thread appoggio = new Thread(new ParameterizedThreadStart(ThreadAscoltoClient));
appoggio.IsBackground = true;
appoggio.Start(conn);
updateUI(conn.RemoteMachineName+" has connected");
}
}
private void ThreadAscoltoClient(object obj)
{
BluetoothClient clientServer = (BluetoothClient)obj;
Stream streamServer = clientServer.GetStream();
streamServer.ReadTimeout=1000;
while (clientServer.Connected)
{
try
{
int bytesDaLeggere = clientServer.Available;
if (bytesDaLeggere > 0)
{
byte[] bytesLetti = new byte[bytesDaLeggere];
int byteLetti = 0;
while (bytesDaLeggere > 0)
{
int bytesDavveroLetti = streamServer.Read(bytesLetti, byteLetti, bytesDaLeggere);
bytesDaLeggere -= bytesDavveroLetti;
byteLetti += bytesDavveroLetti;
}
updateUI("message sent from "+clientServer.RemoteMachineName+": " + System.Text.Encoding.Default.GetString(bytesLetti));
}
}
catch { }
Thread.Sleep(0);
}
updateUI(clientServer.RemoteMachineName + " has gone");
}
private void updateUI(string message)
{
Func<int> del = delegate()
{
textBox1.AppendText(message + System.Environment.NewLine);
return 0;
};
Invoke(del);
}
private void updateConnList()
{
Func<int> del = delegate()
{
listaSensori.Items.Clear();
foreach (BluetoothClient d in connessioniServer)
{
listaSensori.Items.Add(d.RemoteMachineName);
}
return 0;
};
try
{
Invoke(del);
}
catch { }
}
I don't exactly understand how you do it right now (the italian names are not helping...) but maybe my solution can help you.
first of all, bluetooth classic does not support broadcast. so you have to deliver at one at a time.
i do connect to 7 serial port devices at a time, using 7 threads. then i tell every thread to send data. this is very close to same time, but of course not exactly.
let me know if that helps or if you need a code example.
I building a client/server chat app , where the server is listening on IP number 127.0.0.1 and port 1212 , and clients are supposed to connect to that IP & Port .
The problem - in the following order :
I run the server on my computer , listening on (127.0.0.1 & port 1212)
I'm also running a client on my computer (the same computer as #1) that successfully connects to the server (127.0.0.1 & port 1212)
I'm running another client from a different IP , but when trying connect to the server (127.0.0.1 & port 1212) the attempt failed . In this IP , I do not run another server !!!
I don't understand the reason for that ... here is the code :
Server side :
public partial class ServerForm : Form
{
private TcpListener m_tcpServer;
private TcpClient m_tcpClient;
private Thread th;
private ServerNotifier m_chatDialog;
private List<ServerNotifier> m_formArray = new List<ServerNotifier>();
private ArrayList m_threadArray = new ArrayList();
public delegate void ChangedEventHandler(object sender, EventArgs e);
public event ChangedEventHandler m_Changed;
public delegate void SetListBoxItem(String str, String type);
// some code
public void StartListen()
{
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
m_tcpServer = new TcpListener(localAddr, Int32.Parse(tbPortNumber.Text));
m_tcpServer.Start();
// Keep on accepting Client Connection
while (true)
{
// New Client connected, call Event to handle it.
Thread t = new Thread(new ParameterizedThreadStart(NewClient));
m_tcpClient = m_tcpServer.AcceptTcpClient();
t.Start(m_tcpClient);
}
}
}
The winform of the server ....
Client side :
public partial class ClientForm : Form
{
// to know when a button was clicked
private bool m_connectionEstablished = false;
private bool m_enterKeyPressed = false;
private bool m_notRunning = false; // flip this when the server is not running
private NetworkStream m_ns = null;
private StateObject m_state = null;
private TcpClient m_clientTcpConnection = null;
// ip and m_username entered by the client
private String m_ipNumberString = String.Empty;
private String m_username = String.Empty;
private int m_port = 0;
public bool StartTheClient(int m_port)
{
byte[] data = new byte[1024];
string inputFromClient = "";
string portString = "";
try
{
// "127.0.0.1"
this.m_clientTcpConnection = new TcpClient(this.m_ipNumberString , this.m_port);
}
catch (Exception e)
{
// this.rtbClientChat.SelectionColor = Color.LimeGreen;
this.m_notRunning = true; // m_clientTcpConnection is not running
MessageBox.Show("The server is currently not running , try again later!");
// connection failed
return false;
}
this.rtbClientChat.SelectedText = "Connected to the Server...";
String local_IP = ((IPEndPoint)m_clientTcpConnection.Client.LocalEndPoint).Address.ToString();
String local_Port = ((IPEndPoint)m_clientTcpConnection.Client.LocalEndPoint).Port.ToString();
this.rtbClientChat.SelectedText = "\nConnected on IP address " + local_IP + " and Port " + local_Port;
this.rtbClientChat.SelectedText = "\nEnter a message to send to the Server";
this.m_ns = m_clientTcpConnection.GetStream();
this.m_state = new StateObject();
this.m_state.workSocket = m_clientTcpConnection.Client;
this.m_clientTcpConnection.Client.BeginReceive(m_state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(OnReceive), m_state);
// connection established successfully
this.m_connectionEstablished = true;
return true;
}
/// <summary>
/// connet/disconnect
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (this.connectionLabel.Checked == true)
{
// then the user checked the "connet/disconnect" checkbox
// now check if the user also filled the m_port number
try
{
// trying to check if the user entered something is the m_port box
// grab port number
m_port = Int32.Parse(this.boxPortNumber.Text);
m_ipNumberString = this.ipBoxNumber.Text;
// grab IP number
if (m_ipNumberString == string.Empty)
{
MessageBox.Show("Please enter a valid IP Number!");
this.connectionLabel.Checked = false;
return;
}
// grab username
this.m_username = this.usernameBox.Text;
if (this.m_username == string.Empty)
{
MessageBox.Show("Please enter a Username!");
this.connectionLabel.Checked = false;
return;
}
StartTheClient(m_port);
}
catch (Exception exp)
{
if (this.m_notRunning == true)
{
// then the user tried to initiate connection
// while the m_clientTcpConnection is disconnected
this.m_notRunning = false;
}
else
{
// the user didn't put anything in the m_port box
MessageBox.Show("Please enter a Port number !");
this.connectionLabel.Checked = false;
}
}
}
}
Its winform :
Any idea why this is happening ?
Much appreciated !
127.0.0.1 is a localhost. You should specify the IP of the server in the network. You can easily find the IP of the server by running ipconfig in command prompt.
And the listener should also be started on that IP address.
127.0.0.1 In computer networking, localhost means this computer. So if you run your client on another pc, it will try to connect to the server on that pc, but your server is on another. Set the client IP to the one where you have the server.
127.0.0.1
In case if you have more than one network interface on the server you should start your listener like this, for more details follow the link:
m_tcpServer = new TcpListener(IPAddress.Any, Int32.Parse(tbPortNumber.Text));
TcpListener Constructor
Every device has its own localhost (127.0.0.1).
You cannot connect to another PC localhost (127.0.0.1), so your server should have IP such as 192.168.0.1 with specified port which is reachable from another PC.
If not, everytime it will only try to connect to its own localhost!
normally we just use localhost to test our network program internally. but it won't success if you want test externally with localhost.
127.0.0.1 on any machine refers to itself ( localhost) .
So your client code on different machine need to refer to a server IP.
Every machine has two IP's one is internal 127.0.0.1 and other can be external like 192.168.1.10
You need to provide the client code with a external IP address in that LAN
i'm tryin' to read the content of the packets that i've captured with SharpPCap.
This is my little code
private void button4_Click(object sender, EventArgs e)
{
// Retrieve the device list
var devices = LibPcapLiveDeviceList.Instance;
// Extract a device from the list
var device = devices[1];
// Register our handler function to the
// 'packet arrival' event
device.OnPacketArrival +=
new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
// Open the device for capturing
int readTimeoutMilliseconds = 1000;
if (device is AirPcapDevice)
{
// NOTE: AirPcap devices cannot disable local capture
var airPcap = device as AirPcapDevice;
airPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp, readTimeoutMilliseconds);
}
else if (device is WinPcapDevice)
{
var winPcap = device as WinPcapDevice;
winPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp | SharpPcap.WinPcap.OpenFlags.NoCaptureLocal, readTimeoutMilliseconds);
}
else if (device is LibPcapLiveDevice)
{
var livePcapDevice = device as LibPcapLiveDevice;
livePcapDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
}
else
{
throw new System.InvalidOperationException("unknown device type of " + device.GetType().ToString());
}
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
device.StartCapture();
MessageBox.Show("-- Listening on {0}, hit 'Enter' to stop...",
device.Description);
// Stop the capturing process
device.StopCapture();
// Close the pcap device
device.Close();
}
private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
if (e.Packet.LinkLayerType == PacketDotNet.LinkLayers.Ethernet)
{
var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
var ethernetPacket = (PacketDotNet.EthernetPacket)packet;
MessageBox.Show(System.Text.Encoding.ASCII.GetString(e.Packet.Data));
packetIndex++;
}
}
I capture a byte[] packet but i don't know how can i read the whole server response.
thank you for the help