Socket Session getting closed after single message - c#

Debugging is being using Simple Web Socket Client.
So, my socket gets active on port X,
I successfully get the "Hello new client" message on Client.
When i send the first request/data to the server, server receives it and prints on console.
Post this, as soon as I send another request, session closed event is being triggered.
I checked Session's TimeOut: 60secs and KeepAliveTime: 600secs, which seem fine.
below is the code for SocketServer:
static void Main(string[] args)
{
Console.WriteLine("Press any key to start the server!");
Console.ReadKey();
Console.WriteLine();
var bootstrap = BootstrapFactory.CreateBootstrap();
if (!bootstrap.Initialize())
{
Console.WriteLine("Failed to initialize!");
Console.ReadKey();
return;
}
var result = bootstrap.Start();
Console.WriteLine("Start result: {0}!", result);
if (result == StartResult.Failed)
{
Console.WriteLine("Failed to start!");
Console.ReadKey();
return;
}
foreach (WebSocketServer appS in bootstrap.AppServers)
{
appS.NewDataReceived += new SessionHandler<WebSocketSession, byte[]>(appServer_NewDataReceived);
appS.NewSessionConnected += new SessionHandler<WebSocketSession>(appServer_NewSessionConnected);
appS.SessionClosed += new SessionHandler<WebSocketSession, CloseReason>(appServer_SessionClosed);
appS.NewMessageReceived += new SessionHandler<WebSocketSession, string>(appServer_NewMessageReceived);
}
Console.WriteLine("Press key 'q' to stop it!");
Char input;
while ((input = Console.ReadKey().KeyChar) != 'q')
{
Console.WriteLine();
continue;
}
Console.WriteLine();
//Stop the appServer
bootstrap.Stop();
Console.WriteLine();
Console.WriteLine("The server was stopped!");
Console.ReadKey();
}
private static void appServer_NewDataReceived(WebSocketSession session, byte[] message)
{
Console.WriteLine("Client said: " + message);
//Send the received message back
session.Send("Server responded back: " + message);
}
private static void appServer_NewSessionConnected(WebSocketSession session)
{
Console.WriteLine();
Console.WriteLine("New session connected! Sessions counter: " );
session.Send("Hello new client!");
}
private static void appServer_SessionClosed(WebSocketSession session, CloseReason value)
{
Console.WriteLine();
Console.WriteLine("Client disconnected! Sessions counter: ");
}
private static void appServer_NewMessageReceived(WebSocketSession session, string message)
{
Console.WriteLine("Client said: " + message);
//Send the received message back
session.Send("Server responded back: " + message);
}
Error on close is "Protocol Error"

Related

Actual/Hard Timeout with Ping in C#

Sooo... I found an instance where the specified timeout with Ping.Send() or Ping.SendAsync do not adhere to the specified timeouts or TTLs and I am trying to work around it. When an invalid host is attempted to be pinged the specified timeout is ignored and in my case a full 2 seconds passes before the ping fails. For the project I am working on I need that to be something like 100 ms or less (if the host was valid it would only be a hop or 2 away so 100 ms seems plenty).
I've tried Ping.Send() and Ping.SendAsync and cannot for the life me figure out how to do this. The closest I got was doing a .Close on the AutoResetEvent but I couldn't catch/suppress the error that was created doing that. (Code not shown here)
Here is the current iteration of the code, as you can see I use both .Send and .SendAsync; I would prefer to use SendAsync I think... If you run the code below everything is executed in under 100ms (usually 60ms) for a host on the same network, but if the host in invalid the code doesn't exit till after 2000ms.
//.NETCore.App\3.1.4
// Microsoft Visual Studio Community 2019 - Version 16.5.5
// Microsoft Windows [Version 10.0.18362.836]
using System;
using System.Text;
using System.Net.NetworkInformation;
using System.Threading;
using System.Text.RegularExpressions;
class Program
{
public static void Main(string[] args)
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
string who = String.Empty;
//who = "firewall0"; //Hostname of my local firewall
//who = "www.yahoo.com";
who = "not-a-valid-host";
//who = "10.1.1.151"; //My interface
//who = "localhost"; //Should succeed but error has to be suppressed because of IPv6
//who = "2a03:2880:f131:83:face:b00c:0:25de"; //Facebook IPv6, should fail quickly
//who = "127.0.0.1";
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 1;
int numMaxHops = 1; //Supposedly this is TTL, but after some experimenting it appears to be number of hops not TTL in ms
Ping pingSender = new Ping();
PingOptions options = new PingOptions(numMaxHops, true);
if (true) //Use false to toggle off this section of code while testing
{
AutoResetEvent waiter = new AutoResetEvent(false);
pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
Console.WriteLine("Time to live set to: {0}", options.Ttl);
Console.WriteLine("");
pingSender.SendAsync(who, timeout, buffer, options, waiter);
waiter.WaitOne();
Console.WriteLine("Ping example completed.");
}
if (true) //Use false to toggle off this section of code while testing
{
try
{
PingReply reply = pingSender.Send(who, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
if (reply.Address.ToString() != "::1")
{
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
}
else
{
Console.WriteLine(reply.Status);
}
}
catch (Exception ex)
{
Regex noHostMatch = new Regex("No such host is known");
if (noHostMatch.IsMatch(ex.InnerException.ToString()))
//if (false)
{
Console.WriteLine("No such host is known.");
}
else
{
throw;
}
}
}
watch.Stop();
Console.WriteLine("");
Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
Console.WriteLine("Press the Enter key");
Console.ReadLine();
}//End Main()
private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
Console.WriteLine("Ping canceled.");
// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
((AutoResetEvent)e.UserState).Set();
}
// If an error occurred, display the exception to the user.
if (e.Error != null)
{
Console.WriteLine("Ping failed:");
//Console.WriteLine(e.Error.ToString());
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
else
{
PingReply reply = e.Reply;
DisplayReply(reply);
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
}//End PingCompletedCallback()
public static void DisplayReply(PingReply reply)
{
if (reply == null)
return;
Console.WriteLine("Ping Status: {0}", reply.Status);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
if (reply.Address.ToString() != "::1")
{
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
}
}//End DisplayReply()
Out out from running the above while pinging my local firewall.
Time to live set to: 1
Ping Status: Success
Address: 10.1.1.1
RoundTrip time: 0
Time to live: 64
Don't fragment: False
Buffer size: 32
Ping example completed.
Address: 10.1.1.1
RoundTrip time: 0
Time to live: 64
Don't fragment: False
Buffer size: 32
Execution Time: 61 ms
Press the Enter key
Output when pinging not-a-valid-host
Time to live set to: 1
Ping failed:
Ping example completed.
No such host is known.
Execution Time: 2139 ms
Press the Enter key
^ I want to get that execution time down to under 100ms with an invalid host.
Put the ping call inside a Task and Wait() up to your chosen timeout, after that has completed or timed out, we check to see if reply was set.
I've implemented this into your code below
//.NETCore.App\3.1.4
// Microsoft Visual Studio Community 2019 - Version 16.5.5
// Microsoft Windows [Version 10.0.18362.836]
using System;
using System.Text;
using System.Net.NetworkInformation;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
class Program
{
public static void Main(string[] args)
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
string who = String.Empty;
//who = "firewall0"; //Hostname of my local firewall
//who = "www.yahoo.com";
who = "not-a-valid-host";
//who = "10.1.1.151"; //My interface
//who = "localhost"; //Should succeed but error has to be suppressed because of IPv6
//who = "2a03:2880:f131:83:face:b00c:0:25de"; //Facebook IPv6, should fail quickly
//who = "127.0.0.1";
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 1;
int numMaxHops = 1; //Supposedly this is TTL, but after some experimenting it appears to be number of hops not TTL in ms
Ping pingSender = new Ping();
PingOptions options = new PingOptions(numMaxHops, true);
if (false) //Use false to toggle off this section of code while testing
{
AutoResetEvent waiter = new AutoResetEvent(false);
pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
Console.WriteLine("Time to live set to: {0}", options.Ttl);
Console.WriteLine("");
pingSender.SendAsync(who, timeout, buffer, options, waiter);
waiter.WaitOne();
Console.WriteLine("Ping example completed.");
}
if (true) //Use false to toggle off this section of code while testing
{
try
{
PingReply reply = null;
var t = Task.Run(() =>
{
reply = pingSender.Send(who, timeout, buffer, options);
Console.WriteLine("Ping example completed.");
});
t.Wait(TimeSpan.FromMilliseconds(100));
if (reply == null)
{
Console.WriteLine("timed out");
}
else if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
if (reply.Address.ToString() != "::1")
{
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
}
else
{
Console.WriteLine(reply.Status);
}
}
catch (Exception ex)
{
Regex noHostMatch = new Regex("No such host is known");
if (noHostMatch.IsMatch(ex.InnerException.ToString()))
//if (false)
{
Console.WriteLine("No such host is known.");
}
else
{
throw;
}
}
}
watch.Stop();
Console.WriteLine("");
Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
Console.WriteLine("Press the Enter key");
Console.ReadLine();
}//End Main()
private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
Console.WriteLine("Ping canceled.");
// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
((AutoResetEvent)e.UserState).Set();
}
// If an error occurred, display the exception to the user.
if (e.Error != null)
{
Console.WriteLine("Ping failed:");
//Console.WriteLine(e.Error.ToString());
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
else
{
PingReply reply = e.Reply;
DisplayReply(reply);
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
}//End PingCompletedCallback()
public static void DisplayReply(PingReply reply)
{
if (reply == null)
return;
Console.WriteLine("Ping Status: {0}", reply.Status);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
if (reply.Address.ToString() != "::1")
{
Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
}
}
}//End DisplayReply()
}

Php Client closing when Send request to Supersocket in C#

I have server in c#, client in PHP. I used Supersocket[https://supersocket.codeplex.com/] to communication between client and server.
C# with Supersocket - Serverside
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase;
using SuperSocket.Common;
using SuperSocket.SocketEngine;
using SuperSocket;
using System.Configuration;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press any key to start the WebSocketServer!");
Console.ReadKey();
Console.WriteLine();
var appServer = new AppServer();
//Setup the appServer
if (!appServer.Setup(2020))
{
Console.WriteLine("Failed to setup!");
Console.ReadKey();
return;
}
appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConnected);
appServer.NewRequestReceived += new RequestHandler<AppSession, SuperSocket.SocketBase.Protocol.StringRequestInfo>(appServer_NewRequestReceived);
appServer.SessionClosed += new SessionHandler<AppSession, CloseReason>(appServer_SessionClosed);
Console.WriteLine();
//Try to start the appServer
if (!appServer.Start())
{
Console.WriteLine("Failed to start!");
Console.ReadKey();
return;
}
Console.WriteLine("The server started successfully, press key 'q' to stop it!");
while (Console.ReadKey().KeyChar != 'q')
{
Console.WriteLine();
continue;
}
//Stop the appServer
appServer.Stop();
Console.WriteLine();
Console.WriteLine("The server was stopped!");
Console.ReadKey();
}
static void appServer_NewSessionConnected(AppSession session)
{
session.Send("Swelcome");
}
static void appServer_SessionClosed(AppSession session, CloseReason value)
{
session.Send("Server: " + "welcome");
}
static void appServer_NewRequestReceived(AppSession session, SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo)
{
try
{
switch (requestInfo.Key.ToUpper())
{
case ("ECHO"):
session.Send(requestInfo.Body);
break;
case ("ADD"):
session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
break;
case ("MULT"):
var result = 1;
foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))
{
result *= factor;
}
session.Send(result.ToString());
break;
default:
Console.WriteLine("Default");
session.Send(requestInfo.Body);
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
PHP Code - Client side
class XoneDataReciver
{
var $socketPtr;
function OpenConnection($server, $port)
{
$this->socketPtr = fsockopen($server, $port, $errno, $errstr, 0.4);
if (!$this->socketPtr) {
echo "Network down. Please refresh the page again or try again later."; exit();
} else {
return 0;
}
}
function MakeRequest($action, $params = array())
{
if (!$this->socketPtr)
return "error";
$this->sendRequest($action); //Error - Client closing
return $this->readAnswer(); // Got msg from server
}
function sendRequest($request)
{
fputs($this->socketPtr, $request);
}
}
$xone_ip ="127.0.0.1";
$xone_port = "2020";
$xonerequest = new XoneDataReciver;
$xonerequest->OpenConnection($xone_ip, $xone_port);
?>
I got msg from server to client(PHP). But when I try to send msg from php to c#, SessionClosed event fire and the error shows "Client closing". Anyone help me to communicate php client to c# server via Supersocket. Thanks in advance.
Increasing the MaxConnectionNumber in server configuration worked for me.

send message from my web page (client) to a pc (server)?

i would like to send message from my web page (client) to a pc
Problem comes in when I try to send data. It complains about this line: m_socWorker.Send(byData); Error Message is Object reference not set to an instance of an object.
here is my code
// Counts the pings
private int pingsSent;
// Can be used to notify when the operation completes
AutoResetEvent resetEvent = new AutoResetEvent(false);
public static Socket m_socWorker;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList2.SelectedIndex != null)
{
// Reset the number of pings
pingsSent = 0;
// Clear the textbox of any previous content
TextBox2.Dispose();
TextBox2.Text += "Pinging " + DropDownList1.SelectedValue + " with 32 bytes of data:\r\n\r\n";
// Send the ping
Thread thd = new Thread(new ThreadStart(SendPing));
thd.Start();
//SendPing();
try
{
UdpClient udpclient = new UdpClient();
IPAddress remotipadd = IPAddress.Parse(DropDownList1.SelectedValue);
udpclient.Connect(remotipadd,10001);
byte[] data = new byte[1024];
IPEndPoint senderip = new IPEndPoint(remotipadd, Convert.ToInt32(DropDownList2.SelectedValue));
udpclient.Connect(senderip);
TextBox2.Text += "Connect";
// listbox1.Items.Add("connected");
}
catch (SocketException s)
{
MessageBox.Show(s.Message);
}
}
}
private void SendPing()
{
System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
// Create an event handler for ping complete
pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_Complete);
// Create a buffer of 32 bytes of data to be transmitted.
byte[] packetData = Encoding.ASCII.GetBytes("................................");
// Jump though 50 routing nodes tops, and don't fragment the packet
PingOptions packetOptions = new PingOptions(50, true);
// Send the ping asynchronously
pingSender.SendAsync(DropDownList1.SelectedValue, 5000, packetData, packetOptions, resetEvent);
}
private void pingSender_Complete(object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
TextBox2.Text += "Ping was canceled...\r\n";
// The main thread can resume
((AutoResetEvent)e.UserState).Set();
}
else if (e.Error != null)
{
TextBox2.Text += "An error occured: " + e.Error + "\r\n";
// The main thread can resume
((AutoResetEvent)e.UserState).Set();
}
else
{
PingReply pingResponse = e.Reply;
// Call the method that displays the ping results, and pass the information with it
ShowPingResults(pingResponse);
}
}
public void ShowPingResults(PingReply pingResponse)
{
if (pingResponse == null)
{
// We got no response
TextBox2.Text += "There was no response.\r\n\r\n";
return;
}
else if (pingResponse.Status == IPStatus.Success)
{
// We got a response, let's see the statistics
TextBox2.Text += "Reply from " + pingResponse.Address.ToString() + ": bytes=" + pingResponse.Buffer.Length + " time=" + pingResponse.RoundtripTime + " TTL=" + pingResponse.Options.Ttl + "\r\n";
}
else
{
// The packet didn't get back as expected, explain why
TextBox2.Text += "Ping was unsuccessful: " + pingResponse.Status + "\r\n\r\n";
}
// Increase the counter so that we can keep track of the pings sent
pingsSent++;
// Send 4 pings
if (pingsSent < 4)
{
SendPing();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
Object objData = TextBox2.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
//Session["m_socWorker"] = m_socWorker;
//m_socWorker = (Socket) Session["m_socWorker"];
m_socWorker.Send(byData);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}

How do I impersonate a server with Fiddler core?

I'm trying to debug an app without setting fiddler as its proxy.
To do this, I've setup fiddler.core based app that resides on an other computer in the network and added an entry to hosts file.
Here's the app's code:
private static Proxy googleEndpoint;
static void Main(string[] args)
{
List<Fiddler.Session> oAllSessions =new List<Session>();
Fiddler.FiddlerApplication.BeforeRequest += (i) => Console.WriteLine("Before request: "+i.fullUrl);
FiddlerApplication.AfterSessionComplete += (i) =>
{
Console.WriteLine("After request: "+i.fullUrl);
lock (oAllSessions)
{
oAllSessions.Add(i);
}
};
//https://www.google.com.ua/
googleEndpoint = FiddlerApplication.CreateProxyEndpoint(443, true, "www.google.com.ua");
if (null != googleEndpoint)
{
Console.WriteLine("google.com.ua endpoint mounted");
}
else
{
Console.WriteLine("failed to mount google.com.ua endpoint");
}
Console.ReadKey();
SaveSessionsToDesktop(oAllSessions);
}
private static void SaveSessionsToDesktop(List<Fiddler.Session> oAllSessions)
{
bool bSuccess = false;
string sFilename = DateTime.Now.ToString("hh-mm-ss") + ".saz";
try
{
try
{
Monitor.Enter(oAllSessions);
TranscoderTuple oExporter = FiddlerApplication.oTranscoders.GetExporter("SAZ");
if (null != oExporter)
{
Dictionary<string, object> dictOptions = new Dictionary<string, object>();
dictOptions.Add("Filename", sFilename);
// dictOptions.Add("Password", "pencil");
bSuccess = FiddlerApplication.DoExport("SAZ", oAllSessions.ToArray(), dictOptions, null);
}
else
{
Console.WriteLine("Save failed because the SAZ Format Exporter was not available.");
}
}
finally
{
Monitor.Exit(oAllSessions);
}
WriteCommandResponse(bSuccess ? ("Wrote: " + sFilename) : ("Failed to save: " + sFilename));
}
catch (Exception eX)
{
Console.WriteLine("Save failed: " + eX.Message);
}
}
public static void WriteCommandResponse(string s)
{
ConsoleColor oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(s);
Console.ForegroundColor = oldColor;
}
but when I'm trying to access https://www.google.com.ua from the target machine, the requests now time out.
Fiddler app shows that it has recieved the request in the BeforeRequest event, but it never sends a reply (AfterSessionComplete never gets called).
Why does this happen and how can I fix it?
How do I do the same for port 80?
I trust you're keeping in mind the fact that, unless you reconfigure the client to trust the FiddlerServer's root certificate, it will not issue a HTTPS request to FiddlerCore. It will instead immediately close the connection upon getting the interception certificate.
What do you see if you attach a BeforeResponse event handler? Does it fire?

How to scan an IP Range C#

How to scan a specific range of IP and also increment it to user defined range.. in like most of the port scanners. but how to increase host bits.. it increases network bits..
private static void sendAsyncPingPacket(string hostToPing)
{
try
{
int timeout = 5000;
AutoResetEvent waiter = new AutoResetEvent(false);
Ping pingPacket = new Ping();
//ping completion event reaised
pingPacket.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
string data = "Ping test check";
byte[] byteBuffer = Encoding.ASCII.GetBytes(data);
PingOptions pingOptions = new PingOptions(64, true);
Console.WriteLine("Time to live: {0}", pingOptions.Ttl);
//Console.WriteLine("Don't fragment: {0}", pingOptions.DontFragment);
pingPacket.SendAsync(hostToPing, timeout, byteBuffer, pingOptions, waiter);
//do something useful
waiter.WaitOne();
Console.WriteLine("Ping RoundTrip returned, Do something useful here...");
}
catch (PingException pe)
{
Console.WriteLine("INVALID IP ADDRESS FOUND");
}
catch (Exception ex)
{
Console.WriteLine("Exceptin " + ex.Message);
}
}
private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
try
{
if (e.Cancelled)
{
Console.WriteLine("Ping canceled.");
// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
((AutoResetEvent)e.UserState).Set();
}
// If an error occurred, display the exception to the user.
if (e.Error != null)
{
Console.WriteLine("Ping failed>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
//this will print exception
//Console.WriteLine (e.Error.ToString ());
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
PingReply reply = e.Reply;
DisplayReply(reply);
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
catch (PingException pe)
{
Console.WriteLine("INVALID IP ADDRESS");
}
catch (Exception ex)
{
Console.WriteLine("Exception " + ex.Message);
}
}
public static void DisplayReply (PingReply reply)
{
if (reply == null)
return;
Console.WriteLine ("ping status: {0}", reply.Status);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
//Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}
private static long ToInt(string addr)
{
return (long)(uint)System.Net.IPAddress.NetworkToHostOrder(
(int)System.Net.IPAddress.Parse(addr).Address);
}
private static string ToAddr(long address)
{
return System.Net.IPAddress.Parse(address.ToString()).ToString();
}
static int temp = 0;
private static void scanLiveHosts(string ipFrom, string ipTo)
{
long from = Program.ToInt(ipFrom);
long to = Program.ToInt(ipTo);
long ipLong = Program.ToInt(ipFrom);
while ( from < to)
{
string address = Program.ToAddr(ipLong);
Program.sendAsyncPingPacket(address);
ipLong++;
}
}
static void Main(string[] args)
{
try
{
Program.getDeviceList();
Program.sendAsyncPingPacket("192.168.3.72");
Program.scanLiveHosts("192.168.3.1", "192.168.3.41");
}
catch (InvalidOperationException ioe)
{
Console.WriteLine(ioe.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Main Methods used are
private static long ToInt(string addr)
{
return (long)(uint)System.Net.IPAddress.NetworkToHostOrder(
(int)System.Net.IPAddress.Parse(addr).Address);
}
private static string ToAddr(long address)
{
return System.Net.IPAddress.Parse(address.ToString()).ToString();
}
above post is in depth how to send ping packet and scan network.
Hey i found the code by google, i've make little changes to fit my code and other changes to fit your code... maybe you should think about change:
while ( from < to)
{
string address = Program.ToAddr(ipLong);
Program.sendAsyncPingPacket(address);
ipLong++;
}
to something like:
while ( ipLong < to)
{
string address = Program.ToAddr(ipLong);
Program.sendAsyncPingPacket(address);
ipLong++;
}
or the "quest" for ips will not stop at ToAddr(to)

Categories

Resources