'LANGUAGE/C#'에 해당되는 글 2건

  1. 2015.11.04 오픈된 포트 확인
  2. 2015.11.04 프로세스 정보 얻어 오는 방법

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
,

실행중인 프로세스 이름 받아 오기 : Process[] process = Process.GetProcessByName

실행중인 프로세스 종료 : process[0].KILL()


밑에 표는 도대체 뭔지 모르겠지만 일단 Keep....

ProcessStartInfo CMD = new ProcessStartInfo();

Process pro = new Process();

CMD.FileName = @"cmd"; // 실행할 응용프로그램의 경로를 설정


CMD.Window Style = ProcessWindowStyle.Hidden; // 실행할 프로그램을 숨긴다????

CMD.CreateNoWindow == true; // 실행할 프로그램의 창을 생성하지 않는다???????


CMD.UseShellExecute = false;

// 프로세스를 시작할 때 운영체제 셸을 사용할지 여부를 나타내는 값을 가져오거나 설정한다.

// 라고 MSDN이 그러는데 뭔소린진 잘 모르겠다....?????

CMD.RedirectStandardOutput = true; // CMD 창의 내용을 가져오기

CMD.RedirectStandardInput = true; // CMD 창의 데이터를 보내기

CMD.RedirectStandardError = true; // 오류내용 가져오기


pro.EnableRaisingEvents = false;

// 프로세스가 종료될 때 exited 이벤트를 발생시키지 않는다.

pro.StartInfo = CMD; // ProcessStartInfo의 인스턴트인 CMD를 넣어줌

pro.Start(); // 시작

pro.StandardInput.Write(@"Hi! I'm LOGIC!" + Environment.NewLine);

//마무리로 Environment.NewLine이 꼭 필요하다고 한다.

pro.StandardInput.Close(); // 닫음


textBox1.Text = process.StandardOutput.ReadToEnd();

// 해당 프로세스의 내용을 스트림으로 끝까지 읽어온다.

pro.WaitForExit();

pro.Close(); // 프로세스 종료

// textbox1에 CMD의 내용을 출력한다.


이건 도움이 되겠다!!(표에 안들어갈까...ㅠㅠ)

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

using System;

using System.Collections.Generic;

using System.Diagnostics;

 

namespace ProcessInfoWrite

{

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                Process[] allProc = Process.GetProcesses();    //시스템의 모든 프로세스 정보 출력

                int i = 1;

                Console.WriteLine("****** 모든 프로세스 정보 ******");

                Console.WriteLine("현재 실행중은 모든 프로세스 수 : {0}", allProc.Length);

                foreach (Process p in allProc)

                {

                    Console.WriteLine("***** {0}번째 프로세스 ******", i++);

                    WriteProcessInfo(p);

                    Console.WriteLine();

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

 

        private static void WriteProcessInfo(Process processInfo)

        {

            Console.WriteLine("Process : {0}", processInfo.ProcessName);

            Console.WriteLine("시작시간 : {0}", processInfo.StartTime);

            Console.WriteLine("프로세스 PID : {0}", processInfo.Id);

            Console.WriteLine("메모리 : {0}", processInfo.VirtualMemorySize);

        }

    }

}

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

오픈된 포트 확인  (0) 2015.11.04
Posted by OnewayK
,