C# Testing Multiple Proxies - c#

I've been scratching my head about this. I'm wondering how I can test multiple proxies at once, I know how to test one at a time but that takes alot of time.
I'm using this code to test a proxy
public bool testProxy( string proxy, int port )
{
try
{
WebClient web = new WebClient();
web.Proxy = new WebProxy( proxy, port);
web.DownloadString("http://www.google.com/ncr");
return true;
}
catch
{
return false;
}
}
Now how would I test them with multithreading or whatever I need to use?
Because at the moment I'm doing this when a button is pressed, which is time consuming
if (proxy_list.Count > 0)
{
for (int i = 0; i < proxy_list.Count; i++)
{
string Proxy = proxy_list[i];
string[] vars = Proxy.Split( ':' );
if (vars.Length == 2)
{
proxy = vars[0];
port = int.Parse(vars[1]);
if ( !testProxy( proxy, port ) )
{
proxy_list.RemoveAt(i);
}
}
else
{
proxy_list.RemoveAt(i);
}
textBox3.Text = proxy_list.Count.ToString();
this.Refresh();
}
}
Test proxy function
public void testProxy(string proxy, int port, int listpos)
{
try
{
WebClient web = new WebClient();
web.Proxy = new WebProxy(proxy, port);
web.DownloadString("http://www.google.com/ncr");
}
catch
{
proxy_list.RemoveAt(listpos);
}
}

You can try this (multithread)
if (proxy_list.Count > 0)
{
for (int i = 0; i < proxy_list.Count; i++)
{
string Proxy = proxy_list[i];
string[] vars = Proxy.Split( ':' );
if (vars.Length == 2)
{
proxy = vars[0];
port = int.Parse(vars[1]);
Thread TestProxy = new Thread(testProxy( proxy, port, i));
TestProxy.Start();
}
else
{
proxy_list.RemoveAt(i);
}
textBox3.Text = proxy_list.Count.ToString();
this.Refresh();
}
}
public bool testProxy( string proxy, int port, int listpos )
{
try
{
WebClient web = new WebClient();
web.Proxy = new WebProxy( proxy, port);
web.DownloadString("http://www.google.com/ncr");
return true;
}
catch
{
proxy_list.RemoveAt(listpos);
}
}

Related

C# Socket: Client Mishandle 'a' as the Client's id

There are two programs that I made that didn't work. There are the server and the client. The server accepts many client by giving a user an ID (starting from 0). The server sends out the command to the specific client based up the server's id. (Example: 200 client are connected to 1 server. The server's selected id is '5', so the server will send the command to all of the client, and the client will ask the server what ID he wants to execute his command on, and if it's '5', that client will execute and send data to the server). The client has many commands, but to create the smallest code with the same error, I only use 1 command (dir). Basically, the server sends the command to the client and if it matches with the client current id and the server current id, it will process the command. By default, the server's current ID is 10. Here are the list of the commands to help the people who wants to answer:
Server Command:
list (Shows all of the users ID connected and the server's current ID) --> Happens on server
dir (request the client to send its dir listing) --> Sent by the client, read by the Server
set (set the server's current id to any number) (example: 'set 4')
Client:
using System;
using System.Speech.Synthesis;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace clientControl
{
class Program
{
public static string directory = #"C:\";
public static int id = -10;
public static Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static void Main(string[] args)
{
Connect();
getSession();
ReadResponse(sck);
}
static byte[] readResponseFunc()
{
long fileSize = 0;
string fileSizeInString = null;
byte[] fileSizeInByteArray = new byte[1024];
int fileSizeLength = sck.Receive(fileSizeInByteArray);
for (int i = 0; i < fileSizeLength; i++)
{
fileSizeInString = fileSizeInString + (char)fileSizeInByteArray[i];
}
try
{
fileSize = Convert.ToInt64(fileSizeInString);
}
catch { Console.WriteLine(fileSizeInString); }
sck.Send(Encoding.ASCII.GetBytes("a"));
byte[] responseUnknown = new byte[1];
sck.Receive(responseUnknown);
if (Encoding.ASCII.GetString(responseUnknown) == "b")
{
byte[] dataInByteArray = new byte[fileSize];
int dataLength = sck.Receive(dataInByteArray);
return dataInByteArray;
}
return Encoding.ASCII.GetBytes("ERROR RESPONSE FUNC");
}
static void getSession()
{
byte[] message_1 = Encoding.ASCII.GetBytes("make_id");
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
byte[] receivedID = readResponseFunc();
id = Convert.ToInt32(Encoding.ASCII.GetString(receivedID));
}
static bool SocketConnected(Socket s)
{
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
return true;
}
static void ReadResponse(Socket sck)
{
while (true)
{
if (SocketConnected(sck) == true)
{
try
{
string response = Encoding.ASCII.GetString(readResponseFunc());
byte[] message_1 = Encoding.ASCII.GetBytes("get_id");
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
byte[] response_2InByteArray = readResponseFunc();
string response_2 = Encoding.ASCII.GetString(response_2InByteArray);
if (Convert.ToInt32(response_2) == id)
{
if (response == "dir")
{
string resultOfDirring = "Current Directory: " + directory + "\n\n";
string[] folderListingArray = Directory.GetDirectories(directory);
foreach (string dir in folderListingArray)
{
string formed = "DIRECTORY: " + Path.GetFileName(dir);
resultOfDirring = resultOfDirring + formed + Environment.NewLine;
}
string[] fileListingArray = Directory.GetFiles(directory);
foreach (var file in fileListingArray)
{
FileInfo fileInfo = new FileInfo(file);
string formed = "FILE: " + Path.GetFileName(file) + " - FILE SIZE: " + fileInfo.Length + " BYTES";
resultOfDirring = resultOfDirring + formed + Environment.NewLine;
}
byte[] message_11 = Encoding.ASCII.GetBytes(resultOfDirring);
sck.Send(Encoding.ASCII.GetBytes(message_11.Length.ToString()));
byte[] responseUnknown_11 = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown_11) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_11);
}
}
}
else { }
}
catch { if (SocketConnected(sck) == false) { Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }; }
}
else if (SocketConnected(sck) == false) { Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }
}
}
static void Connect()
{
while (true)
{
try
{
sck.Connect(IPAddress.Parse("127.0.0.1"), 80);
break;
}
catch { }
}
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
namespace serverControl
{
class Program
{
public static int ftpNum = 1;
public static List<int> listOfClient = new List<int>();
public static TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
public static string message = null;
public static int id = 0;
public static int selected_id = 10;
static void Main(string[] args)
{
server.Start();
Thread startHandlingClientThread = new Thread(startHandlingClient);
startHandlingClientThread.Start();
while (true)
{
Console.Write(":> ");
string rawmessage = Console.ReadLine();
if (rawmessage == "list")
{
Console.WriteLine("SELECTED ID: " + selected_id);
Console.WriteLine("List of Clients ID:");
for (int i = 0; i < listOfClient.Count; i++)
{
Console.WriteLine(listOfClient[i]);
}
message = rawmessage+"PREVENT_REPETITION_IN_COMMAND";
}
else if (rawmessage.Contains("set ")) { int wantedChangeId = Convert.ToInt32(rawmessage.Replace("set ", "")); selected_id = wantedChangeId; message = rawmessage+ "PREVENT_REPETITION_IN_COMMAND"; }
else
{
message = rawmessage;
}
}
}
static byte[] readResponseFunc(Socket sck)
{
long fileSize = 0;
string fileSizeInString = null;
byte[] fileSizeInByteArray = new byte[1024];
int fileSizeLength = sck.Receive(fileSizeInByteArray);
for (int i = 0; i < fileSizeLength; i++)
{
fileSizeInString = fileSizeInString + (char)fileSizeInByteArray[i];
}
fileSize = Convert.ToInt64(fileSizeInString);
sck.Send(Encoding.ASCII.GetBytes("a"));
byte[] responseUnknown = new byte[1];
sck.Receive(responseUnknown);
if (Encoding.ASCII.GetString(responseUnknown) == "b")
{
byte[] dataInByteArray = new byte[fileSize];
int dataLength = sck.Receive(dataInByteArray);
return dataInByteArray;
}
return Encoding.ASCII.GetBytes("ERROR RESPONSE FUNC");
}
static void startHandlingClient()
{
while (true)
{
handleClient(server);
}
}
static void handleClient(TcpListener clientToAccept)
{
Socket sck = clientToAccept.AcceptSocket();
Thread myNewThread = new Thread(() => ReadResponse(sck));
myNewThread.Start();
}
static bool SocketConnected(Socket s)
{
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
return true;
}
static void ReadResponse(Socket sck)
{
Thread myNewThread = new Thread(() => SendtoClient(sck));
myNewThread.Start();
Thread.Sleep(2000);
while (true)
{
if (SocketConnected(sck) == true)
{
try
{
byte[] dataInByteArray = readResponseFunc(sck);
string response = Encoding.ASCII.GetString(dataInByteArray);
Console.WriteLine("res: " + response);
if (response != "make_id" && response != "get_id") { Console.WriteLine(response); }
if (response == "make_id")
{
Console.WriteLine("Someone wants an ID");
byte[] message_1 = Encoding.ASCII.GetBytes(id.ToString());
listOfClient.Add(id);
// START
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
id++;
}
if (response == "get_id")
{
byte[] message_1 = Encoding.ASCII.GetBytes(selected_id.ToString());
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
}
}
catch { if (SocketConnected(sck) == false) { Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }; }
}
else if (SocketConnected(sck) == false) { Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }
}
}
static void SendtoClient(Socket sck)
{
string tempmessage = null;
while (true)
{
if (SocketConnected(sck) == true)
{
if (tempmessage != message)
{
if (!message.Contains("PREVENT_REPETITION_IN_COMMAND"))
{
byte[] message_1 = Encoding.ASCII.GetBytes(message);
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
}
tempmessage = message;
}
}
else if (SocketConnected(sck) == false)
{ Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }
}
}
}
}
Problem:
The problem is within the GetSession or the ReadResponseFunc function. The client thinks that his ID received by the server is 'a' (it's suppose to be an integer). I don't want a solution that suggest me to use other libs or
the TcpClient class
Bounty:
I'll put up a bounty with no expiry time to those who solve the problem.
The logic in your code is very confusing. My question to you: Why are you sending 'a' and 'b' back and forth between the server and client? Is it some sort of confirmation that the message has been received?
Anyways, throughout the quick tests I've done just now, it seems that the problem is Line 59 of your server:
sck.Send(Encoding.ASCII.GetBytes("a"));
Here's what I figured out during testing:
Server executes.
Client executes.
Client sends server the length of "make_id" (Line 51 of client)
Client waits for a response to return.
Server reads the value and sends back 'a' (Line 59 of server)
You may want to spend some time to straighten out your protocol so it's less confusing and more organized. That would help people like me and you spot bugs much more easily.
The user 'Bobby' has already found your problem. Credits go to him.
I further suggest that you use less threads, as thread synchronisation needs some effort when doing it right: all data that is accessed from different threads must be secured by locks, so that no outdated values remain in the CPU caches. Use .net Monitor from the "threading synchronisation primitives" for that job.
About the threads themselves:
You should have only one thread in the server. This thread takes all clients from a list (secured by Monitor), in which they were added when connection attempts were received. On each client it checks for incoming messages, evaluates them and replies with own messages if needed.
The client also has just one thread, that will loop (dont forget a sleep in the loop or you will have 100% usage of the used CPU core), send messages when desired and wait for replies when messages were sent.
About the messages:
I already gave some proposals in a comment to Bobby's answer. I suggest you create a CMessage class that has a Serialize() and Deserialze() to create a byte array to send from the CMessage members (serializing the content) or vice versa filling the members from the received bytes. You then may use this class in both programs and you'll have common solution.

stm32f4 discovery sample of using USB to communicate with pc or read/write pendrive using net micro framework

I cannot find any sample of using USB port of STM32F4 Discovery board in .NET Micro Framework. I'm trying to learn how to use USB port to send or write data. Where can I find such examples?
I've tried to make sample application based on https://guruce.com/blogpost/communicating-with-your-microframework-application-over-usb but it doesn't work.
This is part of my code sample:
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Hardware.UsbClient;
using System;
using System.Text;
using System.Threading;
namespace MFConsoleApplication1
{
public class Program
{
private const int WRITE_EP = 1;
private const int READ_EP = 2;
private static bool ConfigureUSBController(UsbController usbController)
{
bool bRet = false;
// Create the device descriptor
Configuration.DeviceDescriptor device = new Configuration.DeviceDescriptor(0xDEAD, 0x0001, 0x0100);
device.bcdUSB = 0x110;
device.bDeviceClass = 0xFF; // Vendor defined class
device.bDeviceSubClass = 0xFF; // Vendor defined subclass
device.bDeviceProtocol = 0;
device.bMaxPacketSize0 = 8; // Maximum packet size of EP0
device.iManufacturer = 1; // String #1 is manufacturer name (see string descriptors below)
device.iProduct = 2; // String #2 is product name
device.iSerialNumber = 3; // String #3 is the serial number
// Create the endpoints
Configuration.Endpoint writeEP = new Configuration.Endpoint(WRITE_EP, Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Write);
writeEP.wMaxPacketSize = 64;
writeEP.bInterval = 0;
Configuration.Endpoint readEP = new Configuration.Endpoint(READ_EP, Configuration.Endpoint.ATTRIB_Bulk | Configuration.Endpoint.ATTRIB_Read);
readEP.wMaxPacketSize = 64;
readEP.bInterval = 0;
Configuration.Endpoint[] usbEndpoints = new Configuration.Endpoint[] { writeEP, readEP };
// Set up the USB interface
Configuration.UsbInterface usbInterface = new Configuration.UsbInterface(0, usbEndpoints);
usbInterface.bInterfaceClass = 0xFF; // Vendor defined class
usbInterface.bInterfaceSubClass = 0xFF; // Vendor defined subclass
usbInterface.bInterfaceProtocol = 0;
// Create array of USB interfaces
Configuration.UsbInterface[] usbInterfaces = new Configuration.UsbInterface[] { usbInterface };
// Create configuration descriptor
Configuration.ConfigurationDescriptor config = new Configuration.ConfigurationDescriptor(500, usbInterfaces);
// Create the string descriptors
Configuration.StringDescriptor manufacturerName = new Configuration.StringDescriptor(1, Consts.MANUFACTURER);
Configuration.StringDescriptor productName = new Configuration.StringDescriptor(2, Consts.PRODUCT_NAME);
Configuration.StringDescriptor serialNumber = new Configuration.StringDescriptor(3, Consts.SERIAL_NO);
Configuration.StringDescriptor displayName = new Configuration.StringDescriptor(4, Consts.DISPLAYED_NAME);
Configuration.StringDescriptor friendlyName = new Configuration.StringDescriptor(5, Consts.FRENDLY_NAME);
// Create the final configuration
Configuration configuration = new Configuration();
configuration.descriptors = new Configuration.Descriptor[]
{
device,
config,
manufacturerName,
productName,
serialNumber,
displayName,
friendlyName
};
try
{
// Set the configuration
usbController.Configuration = configuration;
if (UsbController.ConfigError.ConfigOK != usbController.ConfigurationError)
throw new ArgumentException();
// If all ok, start the USB controller.
bRet = usbController.Start();
}
catch (ArgumentException)
{
Debug.Print(Consts.CONFIG_ERR + usbController.ConfigurationError.ToString());
}
return bRet;
}
private static string GetCommand(byte[] data)
{
return new string(Encoding.UTF8.GetChars(data));
}
private static byte[] GetDataToSend(Reading data, JsonSerializer serializer)
{
return Encoding.UTF8.GetBytes(serializer.Serialize(data));
}
private static void UsbMainLoop(UsbStream usbStream, AnalogInput supplyInput, AnalogInput dataInput, OutputPort recievingDataIndicator, OutputPort seindingDataIndicator, JsonSerializer dataSerializer)
{
byte[] readData = new byte[100];
for (;;)
{
recievingDataIndicator.Write(true);
int bytesRead = usbStream.Read(readData, 0, readData.Length);
recievingDataIndicator.Write(false);
if (bytesRead > 0)
{
string command = GetCommand(readData);
switch (command)
{
case "READ":
seindingDataIndicator.Write(true);
byte[] dataToSend = GetDataToSend(Reading.GetReading(supplyInput, dataInput), dataSerializer);
usbStream.Write(dataToSend, 0, dataToSend.Length);
seindingDataIndicator.Write(false);
break;
}
}
}
}
private static UsbController CheckSupportAndAccessibility(UsbController[] usbControllers, out string message)
{
UsbController usbController = null;
if (0 == usbControllers.Length)
{
message = Consts.USB_NOT_SUPPORTED;
}
else
{
bool foundedFreeUsb = false;
foreach (UsbController controller in usbControllers)
{
if (UsbController.PortState.Stopped == controller.Status)
{
usbController = controller;
foundedFreeUsb = true;
break;
}
}
if (foundedFreeUsb)
{
message = string.Empty;
}
else
{
message = Consts.NO_FREE_USB;
}
}
return usbController;
}
private static void OtherMainProgramLoop()
{
AnalogInput temperature0 = new AnalogInput(Cpu.AnalogChannel.ANALOG_0);
AnalogInput supply0 = new AnalogInput(Cpu.AnalogChannel.ANALOG_1);
double t0, r0, z0;
while (true)
{
z0 = supply0.Read() * 3;
r0 = Reading.GetRt(z0, temperature0.Read() * z0);
t0 = Reading.GetTemp(r0);
Debug.Print("Supply:" + z0.ToString() + "[V]");
Debug.Print("Rt:" + r0.ToString() + "[Ohm]");
Debug.Print("Temperature:" + t0.ToString() + "[^C]");
Thread.Sleep(1000);
}
}
public static void Main()
{
UsbController[] controllers = UsbController.GetControllers();
string msg;
UsbController usbController = CheckSupportAndAccessibility(controllers, out msg);
if (null == usbController)
{
Debug.Print(msg);
OtherMainProgramLoop();
//return;
}
else
{
UsbStream usbStream = null;
try
{
if (ConfigureUSBController(usbController))
usbStream = usbController.CreateUsbStream(WRITE_EP, READ_EP);
else
throw new Exception();
}
catch (Exception)
{
Debug.Print(Consts.USB_CREATE_STREAM_ERR + usbController.ConfigurationError.ToString());
OtherMainProgramLoop();
//return;
}
AnalogInput temperatureSource = new AnalogInput(Cpu.AnalogChannel.ANALOG_0);
AnalogInput supplySource = new AnalogInput(Cpu.AnalogChannel.ANALOG_1);
OutputPort ledGreen = new OutputPort((Cpu.Pin)60, false);
OutputPort ledYellow = new OutputPort((Cpu.Pin)61, false);
UsbMainLoop(usbStream, supplySource, temperatureSource, ledYellow, ledGreen, new JsonSerializer());
usbStream.Close();
}
}
}
}
Thanks for any help.

Can't send udp packet with pcapdotnet

My code has shown below:
i already setup winpcap too. There arent any problem with programs which used by pcapdotnet
i think problem should be in layers but i dont know very well.
Console.Write("\r IP:Port = ");
string[] answer = Console.ReadLine().Split(':');
//answer[0] = ip , answer[1] = port
Console.WriteLine(answer[0] + "-"+answer[1]);
Attack_Void(answer[0], Convert.ToInt32(answer[1]));
Console.ReadKey();
}
private static void Attack_Void (string ip,int port)
{
try
{
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
PacketDevice selectedDevice = allDevices[0];
Console.WriteLine(selectedDevice.Description);
PacketCommunicator communicator = selectedDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000);
while (true)
{
Thread tret = new Thread(() => Attack_Thread(communicator, ip, port));
tret.Start();
tret.Join();
tret.Abort();
}
} catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private static void Attack_Thread(PacketCommunicator comm,string ip,int port)
{
string rnd_ip = random_ip();
comm.SendPacket(UdpPacket(rnd_ip,ip,port,false,100));
//comm.SendPacket(Udp_Pack_2());
PacketCounter++;
Console.WriteLine("Veriler {0} ip adresine, {1} ip adresinden gönderildi. NO: {2} ",ip,rnd_ip,Convert.ToString(PacketCounter));
}
private static string random_ip()
{
string srcip = rnd.Next(0, 255) + "." + rnd.Next(0, 255) + "." + rnd.Next(0, 255) + "." + rnd.Next(0, 255);
return srcip;
}
private static Packet UdpPacket(string src_ip, string rem_ip, int rem_port, bool default_port, int src_port)
{
int port;
if (default_port == true)
{
port = src_port;
} else { port = rnd.Next(0, 65535); }
EthernetLayer ethernetLayer = new EthernetLayer {
Source = new MacAddress("48:E2:44:5E:A8:07"),
Destination = new MacAddress("48:E2:44:5E:A8:07") };
IpV4Layer ipv4Layer = new IpV4Layer
{
// Source = new IpV4Address(src_ip),
Source = new IpV4Address("127.0.0.1"),
CurrentDestination = new IpV4Address(rem_ip),
Fragmentation = IpV4Fragmentation.None,
HeaderChecksum = null, // Will be filled automatically.
Identification = 123,
Options = IpV4Options.None,
Protocol = null,
Ttl = 100,
TypeOfService = 0,
};
UdpLayer udpLayer =
new UdpLayer
{
SourcePort = (ushort)port,
DestinationPort = (ushort)rem_port, //port
Checksum = null,
CalculateChecksumValue = true,
};
PayloadLayer payloadLayer =
new PayloadLayer
{
Data = new Datagram(new byte[] { 0x28 }),
};
PacketBuilder builder = new PacketBuilder(ethernetLayer, ipv4Layer, udpLayer, payloadLayer);
return builder.Build(DateTime.Now);
}
These are my code i actually made a udp server to take packet from this program but i cant send packet.
Also it doesnt give any errors.
And i dont know if my network modem enabled spoofing
Try this but remember it works only with IPv4.
using PcapDotNet.Core;
using PcapDotNet.Core.Extensions;
using PcapDotNet.Packets;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace UDP
{
public static class NetworkDevice
{
private static string GetLocalMachineIpAddress()
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
throw new Exception("Network is not available. Please check connection to the internet.");
}
using (Socket socket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
return endPoint.Address.ToString();
}
}
public static PacketDevice GetIpv4PacketDevice()
{
string localMachineIpAddress = GetLocalMachineIpAddress();
IEnumerable<LivePacketDevice> ipV4adapters = LivePacketDevice.AllLocalMachine.Where(w =>
(w.Addresses.Select(s => s.Address.Family))
.Contains(SocketAddressFamily.Internet));
foreach (var adapter in ipV4adapters)
{
var adapterAddresses = adapter.Addresses
.Where(w => w.Address.Family == SocketAddressFamily.Internet)
.Select(s => ((IpV4SocketAddress)s.Address).Address.ToString());
if (adapterAddresses.Contains(localMachineIpAddress))
return adapter;
}
throw new ArgumentException("System didn't find any adapter.");
}
}
public static class DefaultGateway
{
private static IPAddress GetDefaultGateway()
{
return NetworkInterface
.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up)
.SelectMany(n => n.GetIPProperties()?.GatewayAddresses)
.Select(g => g?.Address)
.FirstOrDefault(a => a != null);
}
private static string GetMacAddressFromResultOfARPcommand(string[] commandResult, string separator)
{
string macAddress = commandResult[3].Substring(Math.Max(0, commandResult[3].Length - 2))
+ separator + commandResult[4] + separator + commandResult[5] + separator + commandResult[6]
+ separator + commandResult[7] + separator
+ commandResult[8].Substring(0, 2);
return macAddress;
}
public static string GetMacAddress(char separator = ':')
{
IPAddress defaultGateway = GetDefaultGateway();
if (defaultGateway == null)
{
throw new Exception("System didn't find the default gateway.");
}
string defaultGatewayIpAddress = defaultGateway.ToString();
return GetMacAddress(defaultGatewayIpAddress, separator);
}
public static string GetMacAddress(string ipAddress, char separator)
{
Process process = new Process();
process.StartInfo.FileName = "arp";
process.StartInfo.Arguments = "-a " + ipAddress;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
string strOutput = process.StandardOutput.ReadToEnd();
string[] substrings = strOutput.Split('-');
if (substrings.Length <= 8)
{
throw new Exception("System didn't find the default gateway mac address.");
}
return GetMacAddressFromResultOfARPcommand(substrings, separator.ToString());
}
}
public class UdpProcessor
{
private string _destinationMacAddress;
private string _destinationIPAddress;
private ushort _destinationPort;
private string _sourceMacAddress;
private string _sourceIPAddress;
private ushort _sourcePort;
private static LivePacketDevice _device = null;
public UdpProcessor(string destinationIp)
{
_sourcePort = 55555;
_destinationPort = 44444;
_device = NetworkDevice.GetIpv4PacketDevice() as LivePacketDevice;
_destinationIPAddress = destinationIp;
_sourceIPAddress = _device.Addresses[1].Address.ToString().Split(' ')[1]; //todo
_sourceMacAddress = (_device as LivePacketDevice).GetMacAddress().ToString();
_destinationMacAddress = DefaultGateway.GetMacAddress();
}
private EthernetLayer CreateEthernetLayer()
{
return new EthernetLayer
{
Source = new MacAddress(_sourceMacAddress),
Destination = new MacAddress(_destinationMacAddress),
EtherType = EthernetType.None,
};
}
private IpV4Layer CreateIpV4Layer()
{
return new IpV4Layer
{
Source = new IpV4Address(_sourceIPAddress),
CurrentDestination = new IpV4Address(_destinationIPAddress),
Fragmentation = IpV4Fragmentation.None,
HeaderChecksum = null,
Identification = 123,
Options = IpV4Options.None,
Protocol = null,
Ttl = 100,
TypeOfService = 0,
};
}
private UdpLayer CreateUdpLayer()
{
return new UdpLayer
{
SourcePort = _sourcePort,
DestinationPort = _destinationPort,
Checksum = null,
CalculateChecksumValue = true,
};
}
public void SendUDP()
{
EthernetLayer ethernetLayer = CreateEthernetLayer();
IpV4Layer ipV4Layer = CreateIpV4Layer();
UdpLayer udpLayer = CreateUdpLayer();
PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer);
using (PacketCommunicator communicator = _device.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
communicator.SendPacket(builder.Build(DateTime.Now));
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("\r IP:Port = ");
string ipAddress = Console.ReadLine();
new UdpProcessor(ipAddress).SendUDP();
Console.ReadKey();
}
}
}
Result in wireshark:

Inter-process communication sample-server & client C#

Using .NET 4, wpf c#, I am passing method return values and parameters between two processes.
As I need the connection open and active a all times, I have tried my best to minimize the code that is recurring (within the loop) but unless I put this whole code inside the loop it did not succeed (after the first transfer the connection to server was closed), so as it is here, it does work repeatedly.
I was wondering first is this the way it should be coded, all the process including the new instance, dispose, close... within the loop?
Is the only available datatype for inter-process communication to pass as a string (inefficient)?
public void client()
{
for (int i = 0; i < 2; i++)
{
System.IO.Pipes.NamedPipeClientStream pipeClient =
new System.IO.Pipes.NamedPipeClientStream(".", "testpipe",
System.IO.Pipes.PipeDirection.InOut, System.IO.Pipes.PipeOptions.None);
if (pipeClient.IsConnected != true)
{
pipeClient.Connect(550);
}
System.IO.StreamReader sr = new System.IO.StreamReader(pipeClient);
System.IO.StreamWriter sw = new System.IO.StreamWriter(pipeClient);
string status;
status = sr.ReadLine();
if (status == "Waiting")
{
try
{
sw.WriteLine("param1fileName.cs,33" + i);
sw.Flush();
pipeClient.Close();
}
catch (Exception ex) { throw ex; }
}
}
}
public string server()
{
NamedPipeServerStream pipeServer = null;
do
{
try
{
pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4);
StreamReader sr = new StreamReader(pipeServer);
StreamWriter sw = new StreamWriter(pipeServer);
System.Threading.Thread.Sleep(100);
pipeServer.WaitForConnection();
string test;
sw.WriteLine("Waiting");
sw.Flush();
pipeServer.WaitForPipeDrain();
test = sr.ReadLine();
if (!string.IsNullOrEmpty(test))
try
{
System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => MbxTw.Show(Convert.ToInt32(test.Split(',')[1]), test.Split(',')[0], "method()", "Warning!! - " + "content")), System.Windows.Threading.DispatcherPriority.Normal);
}
catch (Exception e)
{
}
}
catch (Exception ex) {
throw ex; }
finally
{
pipeServer.WaitForPipeDrain();
if (pipeServer.IsConnected) { pipeServer.Disconnect(); }
}
} while (true);
}
after a thorough research on inter process communication I have changed the approach from using Named pipes to Memory mapped files,
as it is all rounds winner, no need to recreate it and faster
I present the ultimate partitioned-global-app-inter-process communication
any thoughts on the code will be greatly appreciated!
public class MMFinterComT
{
public EventWaitHandle flagCaller1, flagCaller2, flagReciver1, flagReciver2;
private System.IO.MemoryMappedFiles.MemoryMappedFile mmf;
private System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor;
public virtual string DepositChlName { get; set; }
public virtual string DepositThrdName { get; set; }
public virtual int DepositSize { get; set; }
private System.Threading.Thread writerThread;
private bool writerThreadRunning;
public int ReadPosition { get; set; }
public List<string> statusSet;
private int writePosition;
public int WritePosition
{
get { return writePosition; }
set
{
if (value != writePosition)
{
this.writePosition = value;
this.accessor.Write(WritePosition + READ_CONFIRM_OFFSET, true);
}
}
}
private List<byte[]> dataToSend;
private const int DATA_AVAILABLE_OFFSET = 0;
private const int READ_CONFIRM_OFFSET = DATA_AVAILABLE_OFFSET + 1;
private const int DATA_LENGTH_OFFSET = READ_CONFIRM_OFFSET + 1;
private const int DATA_OFFSET = DATA_LENGTH_OFFSET + 10;
public IpcMMFinterComSF.MMFinterComTStatus IntercomStatus;
public MMFinterComT(string ctrIpcChannelNameStr, string ctrIpcThreadName, int ctrMMFSize)
{
this.DepositChlName = ctrIpcChannelNameStr;
this.Deposit Size = ctrMMFSize;
this.DepositThrdName = ctrIpcThreadName;
mmf = MemoryMappedFile.CreateOrOpen(DepositChlName, DepositSize);
accessor = mmf.CreateViewAccessor(0, DepositSize, System.IO.MemoryMappedFiles.MemoryMappedFileAccess.ReadWrite);//if (started)
//smLock = new System.Threading.Mutex(true, IpcMutxName, out locked);
ReadPosition = -1;
writePosition = -1;
this.dataToSend = new List<byte[]>();
this.statusSet = new List<string>();
}
public bool reading;
public byte[] ReadData;
public void StartReader()
{
if (this.IntercomStatus != IpcMMFinterComSF.MMFinterComTStatus._Null || ReadPosition < 0 || writePosition < 0)
return;
this.IntercomStatus = IpcMMFinterComSF.MMFinterComTStatus.PreparingReader;
System.Threading.Thread t = new System.Threading.Thread(ReaderThread);
t.IsBackground = true;
t.Start();
}
private void ReaderThread(object stateInfo)
{
// Checks if there is something to read.
this.IntercomStatus = IpcMMFinterComSF.MMFinterComTStatus.TryingToRead;
this.reading = accessor.ReadBoolean(ReadPosition + DATA_AVAILABLE_OFFSET);
if (this.reading)
{
this.IntercomStatus = IpcMMFinterComSF.MMFinterComTStatus.ReadingData;
// Checks how many bytes to read.
int availableBytes = accessor.ReadInt32(ReadPosition + DATA_LENGTH_OFFSET);
this.ReadData = new byte[availableBytes];
// Reads the byte array.
int read = accessor.ReadArray<byte>(ReadPosition + DATA_OFFSET, this.ReadData, 0, availableBytes);
// Sets the flag used to signal that there aren't available data anymore.
accessor.Write(ReadPosition + DATA_AVAILABLE_OFFSET, false);
// Sets the flag used to signal that data has been read.
accessor.Write(ReadPosition + READ_CONFIRM_OFFSET, true);
this.IntercomStatus = IpcMMFinterComSF.MMFinterComTStatus.FinishedReading;
}
else this.IntercomStatus = IpcMMFinterComSF.MMFinterComTStatus._Null;
}
public void Write(byte[] data)
{
if (ReadPosition < 0 || writePosition < 0)
throw new ArgumentException();
this.statusSet.Add("ReadWrite:-> " + ReadPosition + "-" + writePosition);
lock (this.dataToSend)
this.dataToSend.Add(data);
if (!writerThreadRunning)
{
writerThreadRunning = true;
writerThread = new System.Threading.Thread(WriterThread);
writerThread.IsBackground = true;
writerThread.Name = this.DepositThrdName;
writerThread.Start();
}
}
public void WriterThread(object stateInfo)
{
while (dataToSend.Count > 0 && !this.disposed)
{
byte[] data = null;
lock (dataToSend)
{
data = dataToSend[0];
dataToSend.RemoveAt(0);
}
while (!this.accessor.ReadBoolean(WritePosition + READ_CONFIRM_OFFSET))
System.Threading.Thread.Sleep(133);
// Sets length and write data.
this.accessor.Write(writePosition + DATA_LENGTH_OFFSET, data.Length);
this.accessor.WriteArray<byte>(writePosition + DATA_OFFSET, data, 0, data.Length);
// Resets the flag used to signal that data has been read.
this.accessor.Write(writePosition + READ_CONFIRM_OFFSET, false);
// Sets the flag used to signal that there are data avaibla.
this.accessor.Write(writePosition + DATA_AVAILABLE_OFFSET, true);
}
writerThreadRunning = false;
}
public virtual void Close()
{
if (accessor != null)
{
try
{
accessor.Dispose();
accessor = null;
}
catch { }
}
if (this.mmf != null)
{
try
{
mmf.Dispose();
mmf = null;
}
catch { }
}
disposed = true;
GC.SuppressFinalize(this);
}
private bool disposed;
}
and usage
instaciant once !
public static bool StartCurProjInterCom(IpcAccessorSetting curSrv, int DepoSize)
{
if(CurProjMMF ==null)
CurProjMMF = new MMFinterComT(curSrv.Channel.ToString(), curSrv.AccThreadName.ToString(), DepoSize);
CurProjMMF.flagCaller1 = new EventWaitHandle(false, EventResetMode.ManualReset, CurProjMMF.DepositThrdName);
CurProjMMF.flagCaller2 = new EventWaitHandle(false, EventResetMode.ManualReset, CurProjMMF.DepositThrdName);
CurProjMMF.flagReciver1 = new EventWaitHandle(false, EventResetMode.ManualReset, IpcAccessorThreadNameS.DebuggerThrd.ToString());
CurProjMMF.ReadPosition = curSrv.AccessorSectorsSets.DepoSects.Setter.Read;
CurProjMMF.WritePosition = curSrv.AccessorSectorsSets.DepoSects.Setter.Write;
Console.WriteLine("MMFInterComSetter.ReadPosition " + CurProjMMF.ReadPosition);
Console.WriteLine("MMFInterComSetter.WritePosition " + CurProjMMF.WritePosition);
CurProjMMF.StartReader();
return true;
}
use many
public static void StartADebugerInterComCall(IpcCarier SetterDataObj)
{
IpcAccessorSetting curSrv = new IpcAccessorSetting(IpcMMf.IPChannelS.Debugger, IpcAccessorThreadNameS.DebuggerThrdCurProj, 0, 5000);
StartCurProjInterCom(curSrv, 10000);
var dataW = SetterDataObj.IpcCarierToByteArray();//System.Text.Encoding.UTF8.GetBytes(msg);
CurProjMMF.Write(dataW);
CurProjMMF.flagReciver1.Set();
CurProjMMF.flagCaller1.WaitOne();
CurProjMMF.flagCaller1.Reset();
}

How to test if a proxy server is working or not?

I've got a pretty big list with proxy servers and their corresponding ports. How can I check, if they are working or not?
Working? Well, you have to use them to see if they are working.
If you want to see if they are online, I guess ping is a first step.
There is a Ping class in .NET.
using System.Net.NetworkInformation;
private static bool CanPing(string address)
{
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(address, 2000);
if (reply == null) return false;
return (reply.Status == IPStatus.Success);
}
catch (PingException e)
{
return false;
}
}
I like to do a WhatIsMyIP check through a proxy as a test.
using RestSharp;
public static void TestProxies() {
var lowp = new List<WebProxy> { new WebProxy("1.2.3.4", 8080), new WebProxy("5.6.7.8", 80) };
Parallel.ForEach(lowp, wp => {
var success = false;
var errorMsg = "";
var sw = new Stopwatch();
try {
sw.Start();
var response = new RestClient {
//this site is no longer up
BaseUrl = "https://webapi.theproxisright.com/",
Proxy = wp
}.Execute(new RestRequest {
Resource = "api/ip",
Method = Method.GET,
Timeout = 10000,
RequestFormat = DataFormat.Json
});
if (response.ErrorException != null) {
throw response.ErrorException;
}
success = (response.Content == wp.Address.Host);
} catch (Exception ex) {
errorMsg = ex.Message;
} finally {
sw.Stop();
Console.WriteLine("Success:" + success.ToString() + "|Connection Time:" + sw.Elapsed.TotalSeconds + "|ErrorMsg" + errorMsg);
}
});
}
However, I might suggest testing explicitly for different types (ie http, https, socks4, socks5). The above only checks https. In building the ProxyChecker for https://theproxisright.com/#proxyChecker, I started w/ the code above, then eventually had to expand for other capabilities/types.
try this:
public static bool SoketConnect(string host, int port)
{
var is_success = false;
try
{
var connsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 200);
System.Threading.Thread.Sleep(500);
var hip = IPAddress.Parse(host);
var ipep = new IPEndPoint(hip, port);
connsock.Connect(ipep);
if (connsock.Connected)
{
is_success = true;
}
connsock.Close();
}
catch (Exception)
{
is_success = false;
}
return is_success;
}
string strIP = "10.0.0.0";
int intPort = 12345;
public static bool PingHost(string strIP , int intPort )
{
bool blProxy= false;
try
{
TcpClient client = new TcpClient(strIP ,intPort );
blProxy = true;
}
catch (Exception ex)
{
MessageBox.Show("Error pinging host:'" + strIP + ":" + intPort .ToString() + "'");
return false;
}
return blProxy;
}
public void Proxy()
{
bool tt = PingHost(strIP ,intPort );
if(tt == true)
{
MessageBox.Show("tt True");
}
else
{
MessageBox.Show("tt False");
}

Categories

Resources