상세 컨텐츠

본문 제목

Ping Source

C#

by 탑~! 2012. 3. 6. 14:22

본문

using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;

public bool PingConnect(string ip, int port)
        {
            bool connect = false;
            try
            {

                //IP Address 할당
                IPAddress ipAddress = IPAddress.Parse(ip);

                //TCP Client 선언
                TcpClient tcpClient = new TcpClient(AddressFamily.InterNetwork);

                Ping pingSender = new Ping();
                PingOptions options = new PingOptions();

                // Use the default Ttl value which is 128,
                // but change the fragmentation behavior.
                options.DontFragment = true;

                // Create a buffer of 32 bytes of data to be transmitted.
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 120;
                PingReply reply = pingSender.Send(ipAddress, timeout, buffer, options);

                if (reply.Status == IPStatus.Success)
                {
                    // Ping 성공시
                    connect = true;
                }
                else
                {
                    // Ping 실패시 강제 Exception
                    throw new Exception();
                }

                return connect;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

관련글 더보기