Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I try to make a winform C# to ping two PC connect through switch.
I want to ping from PC A (server) to PC B (client). Check a connect alive.
PC A has IP = 192.168.1.100 and PC B has IP = 192.168.1.101
Here is my code:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;

namespace ping
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_ping_Click(object sender, EventArgs e)
        {
            Ping p = new Ping();
            PingReply r;
            String s = "192.168.1.101";
            try
            {
                r = p.Send(s);
                if (r.Status == IPStatus.Success)
                {
                    MessageBox.Show("ONLINE");
                }
            }
            catch
            {
                MessageBox.Show("OFFLINE");
            }
        }
    }
}

If two PC connect direct ( no switch between), my code run correct.
In case connect two PC with switch between, iif cable is not broken my code run correct. But if cable is broken, my code not work. It does not show message "OFFLINE".
What wrong whit it? And how can I fix it? Thanks for help.
Posted

Try to add an else statement in your code.
C#
if (r.Status == IPStatus.Success)
{
    MessageBox.Show("ONLINE");
}
else
{
    // Check if you end up here
}



However, I think the asynchronous ping might be a better approach for you.
You can find an example in MSDN: Ping Class[^]
 
Share this answer
 
Comments
Member 10390715 30-Nov-14 6:17am    
ok it work well, thanks for your help.
George Jonsson 30-Nov-14 8:01am    
You are welcome.
using the following code :

C#
private static void Main(string[] args)
        {
            var p = new Ping();
            const string s = "192.168.1.101";
            try
            {
                var r = p.Send(s);
                Console.WriteLine(r.Status == IPStatus.Success ? "ONLINE" : "OFFLINE");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 
Share this answer
 
Comments
Member 10390715 30-Nov-14 6:18am    
Thanks for your help
Member 10711013 1-Dec-14 1:47am    
your wilcome

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900