IP 주소로 PC에 해당 포트가 오픈되어 있는지 확인


using System;

using System.Text;

using System.Net.Sockets;

using System.Net.NetworkInformation;

using System.Net;



public class CheckPort

{


    public static void Main(string[] args)

    {

        try

        {

if (args.Length < 1)

{

Console.WriteLine("Usage : CheckPort.exe [IP] [Port]");

Console.WriteLine("        CheckPort.exe 192.168.0.1 80");

return;

}

string ip = args[0];

int port = Convert.ToInt32(args[1]);

if (PingTest(ip))

{

Console.WriteLine("{0} PING OK", ip);

if (ConnectTest(ip, port))

{

Console.WriteLine("{0}:{1} is open.", ip, port);

}

else

{

Console.WriteLine("{0}:{1} is closed.", ip, port);

}

}

else

{

Console.WriteLine("{0} PING NG", ip);

}

}

        catch (Exception e)

        {

            Console.WriteLine(e.Message);

        }


    }  

private static bool PingTest(string ip)

{

bool result = false;

try

{

Ping pp = new Ping();

PingOptions po = new PingOptions();


po.DontFragment = true;


byte[] buf = Encoding.ASCII.GetBytes("aaaaaaaaaaaaaaaaaaaa");


PingReply reply = pp.Send(

IPAddress.Parse(ip),

10, buf, po

);


if (reply.Status == IPStatus.Success)

{

result= true;

}

else

{

result = false;

}

return result;

}

catch

{

throw;

}

}



private static bool ConnectTest(string ip, int port)

{

bool result = false;


Socket socket = null;

try

{

socket = new Socket(

AddressFamily.InterNetwork,

SocketType.Stream, 

ProtocolType.Tcp

);


socket.SetSocketOption(

SocketOptionLevel.Socket,

SocketOptionName.DontLinger,

false

);



IAsyncResult ret = socket.BeginConnect(ip, port, null, null);


result = ret.AsyncWaitHandle.WaitOne(100, true);

}

catch { }

finally

{

if (socket != null)

{

socket.Close();

}

}

return result;

}



}





netstat 구현


using System;

using System.Net;

using System.Net.Networkinformation


namespace MyNetstat

{

class Program

{

static void Main(string[] args)

{

IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();


IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();

TcpConnectioninformation[] tcpConnections = ipProperties.GetActiveTcpConnections();


foreach(TcpConnectioninformation info in tcpConnections)

{

Console.WriteLine("Local: " + info.LocalEndPoint.Address.ToString() 

+ ":" + info.LocalEndPoint.Port.ToString() 

+ "\nRemote: " + info.RemoteEndPoint.Address.ToString() 

+ ":" + info.RemoteEndPoint.Port.ToString() 

+ "\nState : " + info.State.ToString() + "\n\n");

}

Console.ReadLine();

}

}

} 

'LANGUAGE > C#' 카테고리의 다른 글

프로세스 정보 얻어 오는 방법  (0) 2015.11.04
Posted by OnewayK
,