첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ 네트워크 조사하기

----------------------------------------------------------------------------------------------------


TestCheckNetwork.zip


MainForm.cs

 

 

using System;

using System.Drawing;

using System.IO;

using System.Net.NetworkInformation;

using System.Runtime.InteropServices;

using System.Text;

using System.Threading;

using System.Windows.Forms;

 

namespace TestCheckNetwork

{

    /// <summary>

    /// 메인 폼

    /// </summary>

    public partial class MainForm : Form

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Import

        ////////////////////////////////////////////////////////////////////////////////////////// Static

        //////////////////////////////////////////////////////////////////////////////// Private

 

        #region 사운드 연주 시작하기 - PlaySoundStart(filePath, moduleHandle, playSoundFlag)

 

        /// <summary>

        /// 사운드 연주 시작하기

        /// </summary>

        /// <param name="filePath">파일 경로</param>

        /// <param name="moduleHandle">모듈 핸들</param>

        /// <param name="playSoundFlag">사운드 연주 플래그</param>

        /// <returns>처리 결과</returns>

        [DllImport("winmm.DLL", EntryPoint = "PlaySound", SetLastError = true)]

        private static extern bool PlaySoundStart(string filePath, IntPtr moduleHandle, PlaySoundFlag playSoundFlag);

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Enumeration

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region 사운드 연주 플래그 - PlaySoundFlag

 

        /// <summary>

        /// 사운드 연주 플래그

        /// </summary>

        private enum PlaySoundFlag : int

        {

            SND_SYNC      = 0x0000,

            SND_ASYNC     = 0x0001,

            SND_NODEFAULT = 0x0002,

            SND_LOOP      = 0x0008,

            SND_NOSTOP    = 0x0010,

            SND_NOWAIT    = 0x00002000,

            SND_FILENAME  = 0x00020000,

            SND_RESOURCE  = 0x00040004

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// PING

        /// </summary>

        private Ping ping = new Ping();

 

        /// <summary>

        /// PING 옵션

        /// </summary>

        private PingOptions pingOptions = new PingOptions();

 

        /// <summary>

        /// PING 데이터

        /// </summary>

        private string pingData = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // 32바이트

 

        /// <summary>

        /// 타임 아웃 시간

        /// </summary>

        private const int TIME_OUT = 120;

 

        /// <summary>

        /// 사운드 스레드

        /// </summary>

        private Thread soundThread;

 

        /// <summary>

        /// 호스트 카운트

        /// </summary>

        private int hostCount = 0;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainForm()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainForm()

        {

            InitializeComponent();

        }

 

        #endregion        

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Method

 

        #region 리스트 뷰 항목 추가하기 - AddListViewItem(host, description)

 

        /// <summary>

        /// 리스트 뷰 항목 추가하기

        /// </summary>

        /// <param name="host">호스트</param>

        /// <param name="description">설명</param>

        public void AddListViewItem(string host, string description)

        {

            string[] valueArray = new string[8];

 

            valueArray[0] = host;

            valueArray[1] = description;

 

            ListViewItem listViewItem = new ListViewItem(valueArray);

 

            this.listView.Items.Add(listViewItem);

 

            for(int column = 2; column < 7; column++)

            {

                this.listView.Items[this.listView.Items.Count - 1].SubItems[column].Text = string.Empty;

            }

 

            this.listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);

            this.listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

        }

 

        #endregion

 

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        //////////////////////////////////////////////////////////////////////////////// Event

 

        #region 폼 로드시 처리하기 - Form_Load(sender, e)

 

        /// <summary>

        /// 폼 로드시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void Form_Load(object sender, EventArgs e)

        {

            this.refreshTimeToolStripComboBox.Text = "5 초";

 

            LoadData();

        }

 

        #endregion

        #region 툴 스트립 항목 클릭시 처리하기 - toolStrip_ItemClicked(sender, e)

 

        /// <summary>

        /// 툴 스트립 항목 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void toolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)

        {

            string itemText = e.ClickedItem.Text;

 

            switch(itemText)

            {

                case "AddHost" :

                

                    AddHostForm addHostForm = new AddHostForm(this);

 

                    addHostForm.ShowDialog();

 

                    break;

 

                case "Start" :

 

                    this.timer.Enabled = true;

 

                    this.messageToolStripStatusLabel.Text = "상태 : 시작 ";

 

                    break;

 

                case "Stop" :

 

                    this.timer.Enabled = false;

 

                    this.messageToolStripStatusLabel.Text = "상태 : 정지 ";

 

                    break;

            }

        }

 

        #endregion

        #region 시간 갱신 툴 스트립 콤보 박스 클릭시 처리하기 - refreshTimeToolStripComboBox_Click(sender, e)

 

        /// <summary>

        /// 시간 갱신 툴 스트립 콤보 박스 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void refreshTimeToolStripComboBox_Click(object sender, EventArgs e)

        {

            switch(this.refreshTimeToolStripComboBox.SelectedIndex)

            {

                case 0 : this.timer.Interval = 5000;  break; //  5 초

                case 1 : this.timer.Interval = 10000; break; // 10 초

                case 2 : this.timer.Interval = 15000; break; // 15 초

                case 3 : this.timer.Interval = 20000; break; // 20 초

                case 4 : this.timer.Interval = 30000; break; // 30 초

            }

        }

 

        #endregion

        #region 타이머 틱 처리하기 - timer_Tick(sender, e)

 

        /// <summary>

        /// 타이머 틱 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void timer_Tick(object sender, EventArgs e)

        {

            if(this.listView.Items.Count == 0)

            {

                MessageBox.Show("체크할 IP 정보가 없습니다.", "알림", MessageBoxButtons.OK, MessageBoxIcon.Error);

 

                this.timer.Enabled = false;

            }

            else

            {

                Byte[] byteArray = Encoding.ASCII.GetBytes(this.pingData);

 

                this.pingOptions.DontFragment = true;

 

                for(int i = 0; i < this.listView.Items.Count; i++)

                {

                    PingReply pingReply = this.ping.Send(this.listView.Items[i].SubItems[0].Text, TIME_OUT, byteArray, this.pingOptions);

 

                    if(pingReply.Status == IPStatus.Success)

                    {

                        for(int column = 2; column < 7; column++)

                        {

                            this.listView.Items[i].BackColor = Color.Yellow;

 

                            string[] pingResultArray = new string[]

                            {

                                DateTime.Now.ToString(),

                                pingReply.Buffer.Length.ToString() + " Bytes",

                                pingReply.RoundtripTime.ToString() + " ms",

                                pingReply.Options.Ttl.ToString()

                            };

 

                            if(column < 6)

                            {

                                this.listView.Items[i].SubItems[column].Text = pingResultArray[column - 2];

                            }

                            else

                            {

                                this.listView.Items[i].SubItems[column].Text = "성공";

                            }

                        }

                    }

                    else

                    {

                        for(int column = 2; column < 7; column++)

                        {

                            if(column < 6)

                            {

                                this.listView.Items[i].SubItems[column].Text = string.Empty;

                            }

                            else

                            {

                                this.listView.Items[i].SubItems[column].Text = "실패";

                            }

 

                            this.listView.Items[i].BackColor = Color.Red;

                        }

 

                        this.soundThread = new Thread(PlaySound);

 

                        this.soundThread.Start();

                    }

                }

 

                this.listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);

                this.listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

            }

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////// Function

 

        #region 데이터 로드하기 - LoadData()

 

        /// <summary>

        /// 데이터 로드하기

        /// </summary>

        private void LoadData()

        {

            if(File.Exists("setting.data") == true)

            {

                string line = string.Empty;

 

                using(StreamReader streamReader = new StreamReader("setting.data"))

                {

                    line = streamReader.ReadLine();

 

                    while(line != null)

                    {

                        string host        = streamReader.ReadLine();

                        string description = streamReader.ReadLine();

 

                        AddListViewItem(host, description);

 

                        line = streamReader.ReadLine();

                    }

 

                    streamReader.Close();

                }

            }

        }

 

        #endregion

        #region 사운드 연주하기 - PlaySound()

 

        /// <summary>

        /// 사운드 연주하기

        /// </summary>

        private void PlaySound()

        {

            PlaySoundStart(Application.StartupPath + @"\sound\ping.wav", new System.IntPtr(), PlaySoundFlag.SND_SYNC);

 

            this.soundThread.Abort();

        }

 

        #endregion

    }

}

 

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker

댓글을 달아 주세요