I'm trying to check if computer on the net is online by using code which supposedly to check it by using ARP packets.
I am always getting message that host is offline even when I'm sure that it's online. I have checked on my localhost IP and on some always working IPs such as google.
That could be wrong with this code?
[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(IPAddress DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
private byte[] macAddr = new byte[6];
private uint macAddrLen;
private void Ping(IPAddress address)
{
if (SendARP(address, 0, new byte[6], ref macAddrLen) == 0)
{
open++;
txtDisplay.AppendText("Host " + address + " is open." + Environment.NewLine);
}
else
{
closed++;
txtDisplay.AppendText("Host " + address + " is closed." + Environment.NewLine);
}
}
By using previous code I'm basically trying to do something like following code. But the problem with this code is that when host is closed that it takes like 2 seconds to get the respond which I want to eliminate. Someone suggested to use ARP ping:
private void Ping(IPAddress address)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
if (cbDontFragment.Checked) options.DontFragment = true;
else options.DontFragment = false;
string dataa = string.Empty;
int dataCounter = 0;
options.Ttl = (int)nudTTL.Value;
for (int i = 0; i < nudData.Value; i++)
{
dataCounter++;
if (dataCounter == 10) dataCounter = 0;
dataa += dataCounter.ToString();
}
byte[] buffer = Encoding.ASCII.GetBytes(dataa);
int timeout = 120;
try
{
PingReply reply = pingSender.Send(address, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
open++;
txtDisplay.AppendText("Host " + address + " is open. ");
if (cbDontFragment.Checked) txtDisplay.AppendText(" Don't fragment. ");
txtDisplay.AppendText(" TTL: " + options.Ttl.ToString() + " ");
txtDisplay.AppendText(" Bytes: " + nudData.Value + " ");
txtDisplay.AppendText(Environment.NewLine);
}
else
{
closed++;
txtDisplay.AppendText("Host " + address + " is closed. ");
if (cbDontFragment.Checked) txtDisplay.AppendText(" Don't fragment. ");
txtDisplay.AppendText(" TTL: " + options.Ttl.ToString() + " ");
txtDisplay.AppendText(" Bytes: " + nudData.Value + " ");
txtDisplay.AppendText(Environment.NewLine);
}
}
catch (Exception ex)
{
txtDisplay.SelectedText += Environment.NewLine + ex.Message;
}
}
ARP cannot be used for what you are trying to do. It only works over a local network.
It's purpose is to resolve an IP address (which is routed) to a MAC address (which is not). It is never sent beyond a network segment (a lan)
Related
I am trying to create a GUI to an ESP8266 project that I have already developed. The boards are using the NodeMCU firmware, and I am loading programs on through the ESP8266 Arduino Core. I am using C# for my GUI program on Windows.
Here is my debug code for the ESP8266 (in Arduino):
#include <ESP8266WiFi.h>
String ConnectedMAC[8];
IPAddress ConnectedIP[8];
WiFiClient clientforcom;
void setup() {
WiFi.mode(WIFI_AP_STA);
Serial.begin(9600);
int f = WiFi.scanNetworks();
Serial.println("Scanning Networks");
delay(5000);
for (int n = 0; n < f; n++) {
Serial.println(WiFi.SSID(n));
}
WiFi.begin(ssid, passtring); //SSID and passtring are my home network credentials
delay(2000);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.print("The IP of this node is: ");
Serial.println(WiFi.localIP());
}
void loop() {
MACManagement();
WiFiServer serverforclient(WiFi.localIP(), 25565);
while (!serverforclient.hasClient()) { //this does not work with Socket or delay is too long
delay(50);
Serial.println("Waiting for client");
}
clientforcom = serverforclient.available();
while (clientforcom.available() <= 0) {
delay(50);
Serial.println("Waiting for response");
}
String response = clientforcom.readString();
if (response.startsWith("GetController")) {
Serial.println("Sending String");
clientforcom.println("Returned String");
}
}
void MACManagement() {
unsigned char number_client;
struct station_info *stat_info;
struct ip_addr *IPaddress;
IPAddress address;
int i = 0;
number_client = wifi_softap_get_station_num();
stat_info = wifi_softap_get_station_info();
Serial.print(" Total Connected Clients are = ");
Serial.println(number_client);
while (stat_info != NULL) {
IPaddress = &stat_info->ip;
address = IPaddress->addr;
Serial.print("client= ");
Serial.print(i);
Serial.print(" IP adress is = ");
Serial.print((address));
ConnectedIP[i] = address;
Serial.print(" with MAC adress is = ");
Serial.print(stat_info->bssid[0], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[1], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[2], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[3], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[4], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[5], HEX); Serial.print(" ");
ConnectedMAC[i] = String(stat_info->bssid[0], HEX) + ":" + String(stat_info->bssid[1], HEX) + ":" + String(stat_info->bssid[2], HEX) + ":" + String(stat_info->bssid[3], HEX) + ":" + String(stat_info->bssid[4], HEX) + ":" + String(stat_info->bssid[5], HEX);
stat_info = STAILQ_NEXT(stat_info, next);
i++;
Serial.println();
}
}
and here is my network accessing code in C#:
void loadUI(){
enterIPLabel.Visible=false;
errorBox.Text="Connecting to Leader node";
tcpcom=new TcpClient(leadernode.ToString(),25565);
tcpcom.Connect(leadernode.ToString(),25565);
while(!tcpcom.Connected);
tcpcom.Client.Send(System.Text.Encoding.ASCII.GetBytes("GetController"));
errorBox.Text="Awaiting Node Response";
while(tcpcom.Available<=0); //hopefully this should stop this method from executing until the response is made
//FILL IN CODE FOR RETURN STATEMENT
tabController.Visible=true;
NodeMap.Visible=true;
}
However, when I reach the "Waiting for Client" section of the ESP8266 code and I run the C# program, entering the IP Address into leadernode. I get an error from .NET that states:
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it
I have no idea why the ESP8266 would be refusing the connection, I put delays such that the Software Watch Dog would not initiate, so I don't understand why it would break the program.
I've created a simple server in raspberry pi 3 running Windows 10 IOT Core with uwp(Universal Windows Platform) with this class>
using System;
using System.Diagnostics;
using System.Text;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
namespace UWP_Server
{
public class StreamSocketManager
{
private StreamSocket ConnectionSocket;
public static bool IsServer { get; set; }
private string ServerPort = "8590";
public void Open()
{
StreamSocketListener DataListener = new StreamSocketListener();
DataListener.ConnectionReceived += ConnectionReceived;
DataListener.BindServiceNameAsync(ServerPort).AsTask().Wait();
}
private async void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader;
StringBuilder sb;
string receivedData = null;
using (reader = new DataReader(args.Socket.InputStream))
{
sb = new StringBuilder();
reader.InputStreamOptions = InputStreamOptions.Partial;
reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
reader.ByteOrder = ByteOrder.LittleEndian;
await reader.LoadAsync(256);
while (reader.UnconsumedBufferLength > 0)
{
sb.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(256);
}
reader.DetachStream();
receivedData = sb.ToString();
}
if (receivedData != null)
{
if (IsServer)
{
MainPage.Current.Show("[SERVER] I've received " + receivedData + " from " +
args.Socket.Information.RemoteHostName);
Debug.WriteLine("[SERVER] I've received " + receivedData + " from " +
args.Socket.Information.RemoteHostName +
"\r\nIp: " + args.Socket.Information.LocalAddress + ":" +
args.Socket.Information.LocalPort +
"\r\nProtectionLevel: " + args.Socket.Information.ProtectionLevel +
"\r\nRemoteHostName: " + args.Socket.Information.RemoteHostName +
"\r\nRemoteIP: " + args.Socket.Information.RemoteAddress + ":" +
args.Socket.Information.RemotePort +
"\r\nRemoteServiceName: " + args.Socket.Information.RemoteServiceName
);
Debug.WriteLine("");
Debug.WriteLine("");
SentResponse(args.Socket.Information.RemoteAddress, "Hello " + args.Socket.Information.RemoteHostName);
}
else
{
Debug.WriteLine("[CLIENT] I've received " + receivedData + " from "
+ args.Socket.Information.RemoteHostName +
"\r\nIp: " + args.Socket.Information.LocalAddress + ":" +
args.Socket.Information.LocalPort +
"\r\nProtectionLevel: " + args.Socket.Information.ProtectionLevel +
"\r\nRemoteHostName: " + args.Socket.Information.RemoteHostName +
"\r\nRemoteIP: " + args.Socket.Information.RemoteAddress + ":" +
args.Socket.Information.RemotePort +
"\r\nRemoteServiceName: " + args.Socket.Information.RemoteServiceName
);
Debug.WriteLine("");
Debug.WriteLine("");
}
}
else
Debug.WriteLine("Received data was empty. Check if you sent data.");
}
public async void SentResponse(HostName address, string message)
{
try
{
Debug.WriteLine("Connecting to " + address + Environment.NewLine);
ConnectionSocket = new StreamSocket();
await ConnectionSocket.ConnectAsync(address, ServerPort);
DataWriter SentResponse_Writer = new DataWriter(ConnectionSocket.OutputStream);
string content = message;
byte[] data = Encoding.UTF8.GetBytes(content);
SentResponse_Writer.WriteBytes(data);
await SentResponse_Writer.StoreAsync();
SentResponse_Writer.DetachStream();
SentResponse_Writer.Dispose();
Debug.WriteLine("Connection has been made and your message " + message + " has been sent." + Environment.NewLine);
ConnectionSocket.Dispose();
ConnectionSocket = new StreamSocket();
}
catch (Exception ex)
{
Debug.WriteLine("Failed to connect ");
ex.Exception("SentResponse");
ConnectionSocket.Dispose();
ConnectionSocket = null;
}
}
}
}
everything seems OK and It's worked in as Server.
I run this code in my Windows 10 mobile (as client) and I can received and send messages between my raspberry pi and windows mobile.
Now I want to send and receive message from my android phone.
I tested a-lot of codes but none of them worked to connect android to raspberry pi.
for android I used this nuget package >
https://github.com/rdavisau/sockets-for-pcl
here is my code:
void Send()
{
var client = new TcpClient();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("Ramtin"), 8590);
try
{
client.Connect(ipEndPoint);
if (client.Connected)
{
Debug.WriteLine("Connected to server" + "\n");
var reader = new StreamReader(client.GetStream());
var writer = new StreamWriter(client.GetStream());
writer.AutoFlush = true;
WriteLine("Connected: " + client.Connected);
if (client.Connected)
{
writer.WriteLine("HEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEy");
}
else
{
Debug.WriteLine("send failed !");
}
}
}
catch (Exception ex)
{
ex.Exception("Send");
}
}
"Ramtin" is my raspberry pi host name.
How can I solve this?
Thanks.
Note: I tried to create android as Server and other phones as clients and it's works fine(sending/receiving message). but I don't want android as a server!
Could someone please show me an example of how to make an SSL connection to an IRC server?
I have tried reading about SslStreams but I just don't get it. I am able to connect to IRC without SSL using this:
sock.Connect(server, port);
if (!sock.Connected) {
Console.WriteLine("Failed to connect!");
return;
}
input = new System.IO.StreamReader(sock.GetStream());
output = new System.IO.StreamWriter(sock.GetStream());
output.Write("USER " + nick + " 0 * :" + owner + "\r\n" + "NICK " + nick + "\r\n");
output.Flush();
//Process each line received from irc server
for (buf = input.ReadLine(); ; buf = input.ReadLine()) {
//Display received irc message
//Console.WriteLine(buf);
if (buf.Split(' ')[1] == "332") {
Console.WriteLine(buf.Split(new char[] { ' ' }, 5)[4]);
}
//Send pong reply to any ping messages
if (buf.StartsWith("PING ")) {
output.Write(buf.Replace("PING", "PONG") + "\r\n"); output.Flush();
}
if (buf[0] != ':') continue;
if (buf.Split(' ')[1] == "001") {
output.Write(
"MODE " + nick + " \r\n" +
"JOIN " + chan + "\r\n"
);
output.Flush();
}
}
}
}
Try this:
conn, err = tls.Dial("tcp", HOST+":"+PORT, &tls.Config{InsecureSkipVerify: true})
I am writing a program that will live on a "Super PC" in my lab at work. Its job is to constantly query our customers databases proactively looking for common errors that we encounter.
It accomplishes this by using an adjustable timer and simply running down the list of queries and databases and interpreting the results.(Queries and Database connections are added using a Configuration UI)
This program has a TCP client/server connection with another app that I have written that lives on my team members personal machines. Messages get sent from the Server(Query) program to the client program alerting my team of errors found in the Databases.
The problem I keep encountering is occasionally a message gets sent through the socket at the exact same time a DB connection is made or a query is run and it causes the server program to crash with no explanation.
The methods that run the queries is always called in its own thread as well as the server connection is made in its own thread.
In addition I have placed all of the DB methods and Client Server methods in Try/Catch blocks that are setup to catch all exceptions and display the stack trace, but for some reason when it crashes its not hitting any of the catch.
The runQueries Methods is called off a C# .Net System.Timers.Timer which is supposed to launch a new thread on every tick.
Below are my Client/Server Methods and Query Methods
private void serverMeth()
{
try
{
/*conbox.Text = conbox.Text + "The server is running at port 8001..." + Environment.NewLine;
conbox.Text = conbox.Text + "The local End point is :" + myList.LocalEndpoint + Environment.NewLine;
conbox.Text = conbox.Text + "Waiting for a connection....." + Environment.NewLine;*/
msglist.Add("The server is running at port 8001...");
msglist.Add("The local end point is: " + myList.LocalEndpoint);
msglist.Add("Waiting for a connection...");
writeToLog("Listening for connection at "+myList.LocalEndpoint);
/* Start Listeneting at the specified port */
while (true)
{
gatherErrors();
myList.Start();
//Socket s = myList.AcceptSocket();
s = myList.AcceptSocket();
//conbox.Text = conbox.Text + "Connection accepted from " + s.RemoteEndPoint + Environment.NewLine;
msglist.Add("Connection accepted from " + s.RemoteEndPoint);
writeToLog("Connection Established #" + myList.LocalEndpoint);
byte[] b = new byte[20000];
int k = s.Receive(b);
//conbox.Text = conbox.Text + "Recieved..." + Environment.NewLine;
msglist.Add("Recieved...");
writeToLog("Message Recieved from Command Center");
//for (int i = 0; i < k; i++)
//{ conbox.Text = conbox.Text + Convert.ToChar(b[i]); }
string message = ""; //allows it to store the entire message in one line
string dt = DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss");
string eid = "TEST ID";
for (int i = 0; i < k; i++)
{ message = message + Convert.ToChar(b[i]); }
if (message.Contains(uniquekey))
{
writeToLog("Message contains correct passcode");
message = message.Replace(uniquekey, "");
String[] splits = message.Split(',');
message = message.Replace("," + splits[1], "");
writeToLog("Connection from " + splits[1]);
msglist.Add(message); //this takes the completed message and adds it.
//DO IGNORE STUF HERE
if (!message.Equals(""))
{
//Message contains error key
Error erro = null;
for (int i = 0; i < errorss.Count; i++)
{
if (errorss[i].getKey().Equals(message)) {
erro = errorss[i];
}
}
Stage st = null;
if (erro != null)
{
for (int i = 0; i < stages.Count; i++)
{
if (stages[i].errContainCheck(erro))
{
st = stages[i];
}
}
}
if (st != null)
{
st.addIgnore(erro);
writeToLog("Error: " + erro.getKey() + "ignored");
}
}
//conbox.Text = conbox.Text + Environment.NewLine;
msglist.Add(" ");
string msg = "";
string log = "Error(s): ";
for (int i = 0; i < errorss.Count; i++)
{
msg += errorss[i].getTime() + "|"+errorss[i].getMsg()+"|" + errorss[i].getSite()+"|"+errorss[i].getKey();
msg += ",";
log += errorss[i].getKey()+",";
}
log+= "sent to Command Center";
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(msg));
//conbox.Text = conbox.Text + "\nSent Acknowledgement" + Environment.NewLine;
msglist.Add("\nSent Acknowledgement");
writeToLog(log);
}
else
{
message = "Unauthorized access detected. Disregarding message.";
//.Add(message); //this takes the completed message and adds it.
//conbox.Text = conbox.Text + Environment.NewLine;
msglist.Add(" ");
writeToLog("Passcode mismatch");
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("Access Denied. Unique key mismatch."));
//conbox.Text = conbox.Text + "\nSent Acknowledgement" + Environment.NewLine;
msglist.Add("\nSent Denial Acknowledgement");
}
/* clean up */
s.Close();
myList.Stop();
if (quit == true)
{
break;
}
}
}
catch (Exception err)
{
//conbox.Text = conbox.Text + "Error..... " + err.StackTrace + Environment.NewLine;
msglist.Add("Error..... " + err.StackTrace);
writeToLog("ERROR: "+err.StackTrace);
}
}
private void sasDownload()
{
int selItemList;
selItemList = saerrlist.SelectedIndex;
saerrlist.Items.Clear(); //clears the list before redownload
saerrgrid.Rows.Clear();
try
{
TcpClient tcpclnt = new TcpClient();
//clibox.Text = clibox.Text + "Connecting....." + Environment.NewLine;
tcpclnt.Connect(staralertip.Text, 8001);
// use the ipaddress as in the server program
//clibox.Text = clibox.Text + "Connected" + Environment.NewLine;
//clibox.Text = clibox.Text + "Enter the string to be transmitted : " + Environment.NewLine;
String str = "982jsdf293jsadd02jkdas20dka2";
Stream stm = tcpclnt.GetStream();
if (ackClick)
{
str += ackKey;
ackClick = false;
}
String name = "User not found";
for (int i = 0; i < users.Count(); i++)
{
if(users[i].sys_id.Equals(SNLists.loggedinuser)){
name = users[i].name;
break;
}
}
str += "," + name;
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
//clibox.Text = clibox.Text + "Transmitting....." + Environment.NewLine;
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[20000];
int k = stm.Read(bb, 0, 20000);
string incmsg = "";
for (int i = 0; i < k; i++)
incmsg = incmsg + Convert.ToChar(bb[i]);
string tempmsg = "";
foreach (char c in incmsg)
{
if (c != ',')
{
tempmsg = tempmsg + c;
}
else if (c == ',')
{
saerrlist.Items.Add(tempmsg);
saerrgrid.Rows.Add(tempmsg.Split('|')[0], tempmsg.Split('|')[1], tempmsg.Split('|')[2], tempmsg.Split('|')[3]);
tempmsg = "";
}
}
saerrlist.Items.Add(tempmsg);
//saerrgrid.Rows.Add(tempmsg.Split('|')[0], tempmsg.Split('|')[1], tempmsg.Split('|')[2]);
//MessageBox.Show(incmsg);
tcpclnt.Close();
}
catch (Exception err)
{
//MessageBox.Show("Error..... " + err.StackTrace, "STAR Command Center: Connectivity Error");
staralertTimer.Enabled = false;
MessageBox.Show("Error downloading recent errors from STAR Alert System.\n\nPlease confirm STAR Alert is running " +
"and hit \"Refresh\" in the STAR Alert tab." + "\n" + err, "STAR Command Center: Connectivity Error");
}
saerrlist.SelectedIndex = selItemList;
}
public void runQueries()
{
OracleConnection con = new OracleConnection();
int siteNum = -1;
try
{
writeToLog("Call to runQueries");
List<List<Error>> results = new List<List<Error>>();
for (int i = 0; i < ppreset.getSites().Count(); i++)
{
siteNum = i;
Site s = ppreset.getSites()[i];
if (s.getStatus().Equals("ACTIVE"))
{
//OracleConnection con = new OracleConnection();
String it = "User Id=" + s.getLogin() + ";Password=" + s.getPassword() + ";Data Source=" + s.getDbName();
con.ConnectionString = it;
//con.OpenAsync();
con.Open();
writeToLog("Connection opened for site: " + s.getSite());
List<Error> subResults = new List<Error>();
for (int j = 0; j < s.getQueries().Count(); j++)
{
Query q = s.getQueries()[j];
string sql = q.getCode();
List<string> columns = getColumns(sql);
List<List<String>> mast = new List<List<String>>();
for (int m = 0; m < columns.Count(); m++)
{
mast.Add(new List<String>());
}
OracleCommand cmd = new OracleCommand(sql, con);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
writeToLog("Execute SQL, Begin Reading results...");
// dr.Read();
//List<String> results = new List<String>();
if (dr.HasRows)
{
//MessageBox.Show("has rows");
while (dr.Read())
{
//string result = "";
for (int p = 0; p < columns.Count(); p++)
{
if (columns.Count() != 0)
{
mast[p].Add(dr[columns[p]].ToString());
}
}
//results.Add(result);
}
}
subResults.AddRange(ruleCheck(mast, q.getRules(), s.getQueries()[j], ppreset.getSites()[i].getSite()));
cmd.Dispose();
writeToLog("Done reading");
}
results.Add(subResults);
// con.Dispose();
con.Close();
writeToLog("Connection Closed for site: " + s.getSite());
}
}
//we now have all of the error strings gathered from running all queries on all sites in the given preset
//lets send them to a method that will change the status' of the modules and makem RAVVEEEEE
//update(results);
if (errors == null && results.Count != 0)
{
//MessageBox.Show("errors = results");
errors = results;
writeToLog("First error found...errors = results");
for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results[i].Count; j++)
{
if (foncig.lallerdisc == true)
{
sendLyncMsg(results[i][j].getMsg());
writeToLog("Lync Msg sent");
}
}
}
}
else
{
for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results[i].Count; j++)
{
errors[i].Add(results[i][j]);
writeToLog("Error: " + results[i][j].getKey() + " added");
// MessageBox.Show("Error added to errors");
//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//LYNC STUFF CAN GO HERE///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/////FOR EACH ERROR ADDED TO MASTER LIST SEND LYNC///////////////////////////
//////////////////////////////////////////////////////////////////////////////
if (foncig.lallerdisc == true)
{
sendLyncMsg(results[i][j].getMsg());
writeToLog("Lync msg sent");
}
}
}
}
}
catch (Exception e)
{//MessageBox.Show("Err: " + e);
badConn[siteNum] += "x";
writeToLog("Connection error strike added to " + ppreset.getSites()[siteNum].getSite());
con.Close();
checkForBadConn();
writeToLog( e.StackTrace);
}
//foncig.errors = errors;
//here we will check all of the errors in results against all of the errors in errors
//if the error is not in errors add it
//errors = results;
}
Query timer initialization
queryTimer = new System.Timers.Timer(120000);
queryTimer.Elapsed += queryTimer_Tick;
queryTimer.Enabled = true;
Tick method for query timer
private void queryTimer_Tick(object sender, EventArgs e)
{
GC.Collect();
try
{
runQueries();
}
catch (OracleException err)
{
// MessageBox.Show("Err: " + err);
}
}
How the server thread is started
server = new Thread(serverMeth);
server.Start();
Does anyone have any idea why this might be happening? Both programs work as described and do what they are supposed to its just when more and more clients begin connecting to the server it becomes more and more likely that a TCP connection and DB connection will occur at the same time.
Update 12:20 9/15/14
So I'm trying to upload a pic of the log from the last crash... but i don't have enough rep points... derp, anyway
This time the last line in the log is from a log purge(deletes log entries older than 24 hours)
However the program will only crash when I have the client program set to auto refresh. IE Client app has a button to request messages from server or user can select auto-refresh which sets request function to timer.
My only other thought is that multiple threads are trying to write to the log file at the same time, however my write to log method uses writeLinesAsync() so that shouldn't be a problem?
This issue turned out to be caused by multiple threads trying to write to the log file at the same time.
I resolved it by following #user469104's advice and creating an internal lock object to lock the writeToLog methods.
Both client and server apps have been running for multiple days now without breaking.
Thanks Everyone!
I'm working on a windows form in which I ping a host.
For some reason, I cant get Response.Buffer to work. I tried using HttpContext.Current, and I also double checked I added a reference to both System.Web, and System.Net.NetworkInformation.
Here is the code :
Ping p = new Ping();
PingReply r;
String s = UserInput;
r = p.Send(s);
HttpContext.Current.Response.Buffer = false;
if (r.Status == IPStatus.Success)
{
string got = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "] successful - " + r.Buffer.Length.ToString() + " bytes in " + r.RoundtripTime.ToString() + " ms." + "\n";
string ToSave = ToSave + got;
}
What you are trying to do does not make sense. Pinging a host is to check whether it is alive, not sending / receiving data, what I think you are trying to do.
When you want to communicate between two clients, then TcpClient is probably what you need. Take a look at the docs and demo here.
When just trying to check connectivity, try this:
Ping p = new Ping();
PingReply reply = p.Send("www.contoso.com");
if (reply.Status == IPStatus.Success)
{
...
}