I've made a short program where the user enters an IP address of a computer, and the program proceeds to check if the computer is online by trying to connect to it with port 80 (the assumption is that if a computer is turned on, it's connected to the internet).
Now, the problem is, everytime I click the Start button it does nothing for a few seconds and then it crashes.
Here's the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Online_Checker
{
public partial class Form1 : Form
{
int success;
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipAddress.Text), 80);
while (true)
{
success = 1;
try { client.Connect(ep); }
catch { status.BackColor = Color.Red; status.Text = "OFFLINE"; success = 0; }
if (success == 1)
{
status.BackColor = Color.Red;
status.Text = "ONLINE";
client.Close();
}
Thread.Sleep(5000);
}
}
}
}
As you can see I've even made a delay of 5 seconds between each check to make sure it doesn't crash.
So where's the problem? And how can I solve it?