I have a big list of proxy servers (txt file , Format = ip:port in each line) and wrote the code below for checking them:
public static void MyChecker()
{
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
List<string> list_lines_RemovedDup = new List<string>();
HashSet<string> HS = new HashSet<string>();
int Duplicate_Count = 0;
int badProxy = 0;
int CheckedCount = 0;
foreach (string line in list_lines)
{
string[] line_char = line.Split(':');
string ip = line_char[0];
string port = line_char[1];
if (CanPing(ip))
{
if (SoketConnect(ip, port))
{
if (CheckProxy(ip, port))
{
string ipAndport = ip + ":" + port;
if (HS.Add(ipAndport))
{
list_lines_RemovedDup.Add(ipAndport);
CheckedCount++;
}
else
{
Duplicate_Count++;
CheckedCount++;
}
}
else
{
badProxy++;
CheckedCount++;
}
}
else
{
badProxy++;
CheckedCount++;
}
}
else
{
badProxy++;
CheckedCount++;
}
}
public static bool CanPing(string ip)
{
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(ip, 2000);
if (reply == null)
return false;
return (reply.Status == IPStatus.Success);
}
catch (PingException Ex)
{
return false;
}
}
public static bool SoketConnect(string ip, string 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(ip);
var ipep = new IPEndPoint(hip, int.Parse(port));
connsock.Connect(ipep);
if (connsock.Connected)
{
is_success = true;
}
connsock.Close();
}
catch (Exception)
{
is_success = false;
}
return is_success;
}
public static bool CheckProxy(string ip, string port)
{
try
{
WebClient WC = new WebClient();
WC.Proxy = new WebProxy(ip, int.Parse(port));
WC.DownloadString("http://SpecificWebSite.com");
return true;
}
catch (Exception)
{
return false;
}
}
But I think I should rewrite these codes because they are very slow.
I have bad delays in these lines :
WC.DownloadString("http://SpecificWebSite.com");
and
PingReply reply = ping.Send(ip, 2000);
and this is not good for a big list.
Did I write these codes in the right direction or should i change them(which parts)?
how can i optimze them?
thanks in advance
There are quite a few things you can improve.
These alone should speed up your process by quite a bit.
As requested, here's an example of how to use HttpWebRequests
I might do something like this:
Using a WhatIsMyIP-like REST service (I use one from https://TheProxIsRight.com).
Then As suggested above, I might try parallelize it with something like:
Note, one can also use the REST API on the above site to query for working proxies: https://theproxisright.com/#apidemo
(Disclosure, I worked on the above site)