본문 바로가기

Test Code/C#

[C#] 포트 오픈 여부 확인

IP 주소로 PC에 해당 포트가 오픈되어 있는지 확인하는 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; } }