[C#] 포트가 열려있는지 확인

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;
}
}

 

Post Author: 김 키티

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다