■ 패킷 조회하기

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


TestProject.zip


Protocol.cs

 

 

namespace TestProject

{

    /// <summary>

    /// 프로토콜

    /// </summary>

    public enum Protocol

    {

        /// <summary>

        /// TCP

        /// </summary>

        TCP = 6,

 

        /// <summary>

        /// UDP

        /// </summary>

        UDP = 17,

 

        /// <summary>

        /// UNKNOWN

        /// </summary>

        UNKNOWN = -1

    };

}

 

 

IPHeader.cs

 

 

using System;

using System.IO;

using System.Net;

using System.Windows.Forms;

 

namespace TestProject

{

    /// <summary>

    /// IP 헤더

    /// </summary>

    public class IPHeader

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 버전/헤더 길이

        /// </summary>

        private byte versionAndHeaderLength;

 

        /// <summary>

        /// 차별화 서비스

        /// </summary>

        private byte differentiatedServices;

 

        /// <summary>

        /// 전체 길이

        /// </summary>

        private ushort totalLength;

 

        /// <summary>

        /// 식별

        /// </summary>

        private ushort identification;

 

        /// <summary>

        /// 플래그/오프셋

        /// </summary>

        private ushort flagsAndOffset;

 

        /// <summary>

        /// TTL

        /// </summary>

        private byte ttl;

 

        /// <summary>

        /// 프로토콜

        /// </summary>

        private byte protocol;

 

        /// <summary>

        /// 체크썸

        /// </summary>

        private short checksum;

 

        /// <summary>

        /// 소스 주소

        /// </summary>

        private uint sourceAddress;

 

        /// <summary>

        /// 목적 주소

        /// </summary>

        private uint destinationAddress;

 

        /// <summary>

        /// 헤더 길이

        /// </summary>

        private byte headerLength;

 

        /// <summary>

        /// 데이터 바이트 배열

        /// </summary>

        private byte[] dataByteArray = new byte[4096];

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 버전 - Version

 

        /// <summary>

        /// 버전

        /// </summary>

        public string Version

        {

            get

            {

                if((this.versionAndHeaderLength >> 4) == 4)

                {

                    return "IP v4";

                }

                else if((this.versionAndHeaderLength >> 4) == 6)

                {

                    return "IP v6";

                }

                else

                {

                    return "Unknown";

                }

            }

        }

 

        #endregion

        #region 헤더 길이 - HeaderLength

 

        /// <summary>

        /// 헤더 길이

        /// </summary>

        public string HeaderLength

        {

            get

            {

                return this.headerLength.ToString();

            }

        }

 

        #endregion

        #region 메시지 길이 - MessageLength

 

        /// <summary>

        /// 메시지 길이

        /// </summary>

        public ushort MessageLength

        {

            get

            {

                return (ushort)(this.totalLength - this.headerLength);

            }

        }

 

        #endregion

        #region 차별화 서비스 - DifferentiatedServices

 

        /// <summary>

        /// 차별화 서비스

        /// </summary>

        public string DifferentiatedServices

        {

            get

            {

                return string.Format("0x{0:x2} ({1})", this.differentiatedServices, this.differentiatedServices);

            }

        }

 

        #endregion

        #region 플래그 - Flags

 

        /// <summary>

        /// 플래그

        /// </summary>

        public string Flags

        {

            get

            {

                int flags = this.flagsAndOffset >> 13;

 

                if(flags == 2)

                {

                    return "Don't fragment";

                }

                else if(flags == 1)

                {

                    return "More fragments to come";

                }

                else

                {

                    return flags.ToString();

                }

            }

        }

 

        #endregion

        #region 단편화 오프셋 - FragmentationOffset

 

        /// <summary>

        /// 단편화 오프셋

        /// </summary>

        public string FragmentationOffset

        {

            get

            {

                int offset = this.flagsAndOffset << 3;

 

                offset >>= 3;

 

                return offset.ToString();

            }

        }

 

        #endregion

        #region TTL - TTL

 

        /// <summary>

        /// TTL

        /// </summary>

        public string TTL

        {

            get

            {

                return this.ttl.ToString();

            }

        }

 

        #endregion

        #region 프로토콜 타입 - ProtocolType

 

        /// <summary>

        /// 프로토콜 타입

        /// </summary>

        public Protocol ProtocolType

        {

            get

            {

                if(this.protocol == 6)

                {

                    return Protocol.TCP;

                }

                else if(this.protocol == 17)

                {

                    return Protocol.UDP;

                }

                else

                {

                    return Protocol.UNKNOWN;

                }

            }

        }

 

        #endregion

        #region 체크썸 - Checksum

 

        /// <summary>

        /// 체크썸

        /// </summary>

        public string Checksum

        {

            get

            {

                return string.Format("0x{0:x2}", this.checksum);

            }

        }

 

        #endregion

        #region 소스 주소 - SourceAddress

 

        /// <summary>

        /// 소스 주소

        /// </summary>

        public IPAddress SourceAddress

        {

            get

            {

                return new IPAddress(this.sourceAddress);

            }

        }

 

        #endregion

        #region 목적 주소 - DestinationAddress

 

        /// <summary>

        /// 목적 주소

        /// </summary>

        public IPAddress DestinationAddress

        {

            get

            {

                return new IPAddress(this.destinationAddress);

            }

        }

 

        #endregion

        #region 전체 길이 - TotalLength

 

        /// <summary>

        /// 전체 길이

        /// </summary>

        public string TotalLength

        {

            get

            {

                return this.totalLength.ToString();

            }

        }

 

        #endregion

        #region 식별 - Identification

 

        /// <summary>

        /// 식별

        /// </summary>

        public string Identification

        {

            get

            {

                return this.identification.ToString();

            }

        }

 

        #endregion

        #region 데이터 바이트 배열 - DataByteArray

 

        /// <summary>

        /// 데이터 바이트 배열

        /// </summary>

        public byte[] DataByteArray

        {

            get

            {

                return this.dataByteArray;

            }

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - IPHeader(sourceByteArray, countReceived)

 

        /// <summary>

        /// 생성자

        /// </summary>

        /// <param name="sourceByteArray">소스 바이트 배열</param>

        /// <param name="countReceived">수신 카운트</param>

        public IPHeader(byte[] sourceByteArray, int countReceived)

        {

            try

            {

                MemoryStream memoryStream = new MemoryStream(sourceByteArray, 0, countReceived);

                BinaryReader binaryReader = new BinaryReader(memoryStream);

 

                this.versionAndHeaderLength = binaryReader.ReadByte();

                this.differentiatedServices = binaryReader.ReadByte();

                this.totalLength            = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.identification         = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.flagsAndOffset         = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.ttl                    = binaryReader.ReadByte();

                this.protocol               = binaryReader.ReadByte();

                this.checksum               = IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.sourceAddress          = (uint)(binaryReader.ReadInt32());

                this.destinationAddress     = (uint)(binaryReader.ReadInt32());

                this.headerLength           = this.versionAndHeaderLength;

                this.headerLength <<= 4;

                this.headerLength >>= 4;

                this.headerLength *=  4;

 

                Array.Copy(sourceByteArray, this.headerLength, this.dataByteArray, 0, this.totalLength - this.headerLength);

            }

            catch(Exception exception)

            {

                MessageBox.Show

                (

                    exception.Message,

                    "ERROR",

                    MessageBoxButtons.OK,

                    MessageBoxIcon.Error

                );

            }

        }

 

        #endregion

    }

}

 

 

TCPHeader.cs

 

 

using System;

using System.Net;

using System.IO;

using System.Windows.Forms;

 

namespace TestProject

{

    /// <summary>

    /// TCP 헤더

    /// </summary>

    public class TCPHeader

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 소스 포트

        /// </summary>

        private ushort sourcePort;

 

        /// <summary>

        /// 목적 포트

        /// </summary>

        private ushort destinationPort;

 

        /// <summary>

        /// 시퀀스 번호

        /// </summary>

        private uint sequenceNumber = 555;

 

        /// <summary>

        /// 승인 번호

        /// </summary>

        private uint acknowledgementNumber = 555;

 

        /// <summary>

        /// 데이터 오프셋/플래그

        /// </summary>

        private ushort dataOffsetAndFlags = 555;

 

        /// <summary>

        /// 윈도우 크기

        /// </summary>

        private ushort windowSize = 555;

 

        /// <summary>

        /// 체크썸

        /// </summary>

        private short checksum = 555;

 

        /// <summary>

        /// 긴급 포인터

        /// </summary>

        private ushort urgentPointer;      

 

        /// <summary>

        /// 헤더 길이

        /// </summary>

        private byte headerLength;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 소스 포트 - SourcePort

 

        /// <summary>

        /// 소스 포트

        /// </summary>

        public string SourcePort

        {

            get

            {

                return this.sourcePort.ToString();

            }

        }

 

        #endregion

        #region 목적 포트 - DestinationPort

 

        /// <summary>

        /// 목적 포트

        /// </summary>

        public string DestinationPort

        {

            get

            {

                return this.destinationPort.ToString();

            }

        }

 

        #endregion

        #region 시퀀스 번호 - SequenceNumber

 

        /// <summary>

        /// 시퀀스 번호

        /// </summary>

        public string SequenceNumber

        {

            get

            {

                return this.sequenceNumber.ToString();

            }

        }

 

        #endregion

        #region 승인 번호 - AcknowledgementNumber

 

        /// <summary>

        /// 승인 번호

        /// </summary>

        public string AcknowledgementNumber

        {

            get

            {

                if((this.dataOffsetAndFlags & 0x10) != 0)

                {

                    return this.acknowledgementNumber.ToString();

                }

                else

                {

                    return string.Empty;

                }

            }

        }

 

        #endregion

        #region 헤더 길이 - HeaderLength

 

        /// <summary>

        /// 헤더 길이

        /// </summary>

        public string HeaderLength

        {

            get

            {

                return this.headerLength.ToString();

            }

        }

 

        #endregion

        #region 윈도우 크기 - WindowSize

 

        /// <summary>

        /// 윈도우 크기

        /// </summary>

        public string WindowSize

        {

            get

            {

                return this.windowSize.ToString();

            }

        }

 

        #endregion

        #region 플래그 - Flags

 

        /// <summary>

        /// 플래그

        /// </summary>

        public string Flags

        {

            get

            {

                int flags = this.dataOffsetAndFlags & 0x3F;

 

                string flagsString = string.Format("0x{0:x2} (", flags);

 

                if((flags & 0x01) != 0)

                {

                    flagsString += "FIN, ";

                }

 

                if((flags & 0x02) != 0)

                {

                    flagsString += "SYN, ";

                }

 

                if((flags & 0x04) != 0)

                {

                    flagsString += "RST, ";

                }

 

                if((flags & 0x08) != 0)

                {

                    flagsString += "PSH, ";

                }

 

                if((flags & 0x10) != 0)

                {

                    flagsString += "ACK, ";

                }

 

                if((flags & 0x20) != 0)

                {

                    flagsString += "URG";

                }

 

                flagsString += ")";

 

                if(flagsString.Contains("()"))

                {

                    flagsString = flagsString.Remove(flagsString.Length - 3);

                }

                else if(flagsString.Contains(", )"))

                {

                    flagsString = flagsString.Remove(flagsString.Length - 3, 2);

                }

 

                return flagsString;

            }

        }

 

        #endregion

        #region 체크썸 - Checksum

 

        /// <summary>

        /// 체크썸

        /// </summary>

        public string Checksum

        {

            get

            {

                return string.Format("0x{0:x2}", this.checksum);

            }

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - TCPHeader(sourceByteArray, countReceived)

 

        /// <summary>

        /// 생성자

        /// </summary>

        /// <param name="sourceByteArray">소스 바이트 배열</param>

        /// <param name="countReceived">수신 카운트</param>

        public TCPHeader(byte[] sourceByteArray, int countReceived)

        {

            try

            {

                MemoryStream memoryStream = new MemoryStream(sourceByteArray, 0, countReceived);

                BinaryReader binaryReader = new BinaryReader(memoryStream);

                

                this.sourcePort            = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.destinationPort       = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.sequenceNumber        = (uint)IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());

                this.acknowledgementNumber = (uint)IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());

                this.dataOffsetAndFlags    = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.windowSize            = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.checksum              = (short)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.urgentPointer         = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                this.headerLength          = (byte)(this.dataOffsetAndFlags >> 12);

 

                this.headerLength *= 4;

            }

            catch(Exception exception)

            {

                MessageBox.Show

                (

                    exception.Message,

                    "ERROR",

                    MessageBoxButtons.OK,

                    MessageBoxIcon.Error

                );

            }

        }

 

        #endregion

    }

}

 

 

UDPHeader.cs

 

 

using System;

using System.Net;

using System.IO;

 

namespace TestProject

{

    /// <summary>

    /// UDP 헤더

    /// </summary>

    public class UDPHeader

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 소스 포트

        /// </summary>

        private ushort sourcePort;

 

        /// <summary>

        /// 목적 포트

        /// </summary>

        private ushort destinationPort;

 

        /// <summary>

        /// 길이

        /// </summary>

        private ushort length;

 

        /// <summary>

        /// 체크썸

        /// </summary>

        private short checksum;

 

        /// <summary>

        /// 데이터 바이트 배열

        /// </summary>

        private byte[] dataByteArray = new byte[4096];

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 소스 포트 - SourcePort

 

        /// <summary>

        /// 소스 포트

        /// </summary>

        public string SourcePort

        {

            get

            {

                return this.sourcePort.ToString();

            }

        }

 

        #endregion

        #region 목적 포트 - DestinationPort

 

        /// <summary>

        /// 목적 포트

        /// </summary>

        public string DestinationPort

        {

            get

            {

                return this.destinationPort.ToString();

            }

        }

 

        #endregion

        #region 길이 - Length

 

        /// <summary>

        /// 길이

        /// </summary>

        public string Length

        {

            get

            {

                return this.length.ToString();

            }

        }

 

        #endregion

        #region 체크썸 - Checksum

 

        /// <summary>

        /// 체크썸

        /// </summary>

        public string Checksum

        {

            get

            {

                return string.Format("0x{0:x2}", this.checksum);

            }

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - UDPHeader(sourceByteArray, countReceived)

 

        /// <summary>

        /// 생성자

        /// </summary>

        /// <param name="sourceByteArray">소스 바이트 배열</param>

        /// <param name="countReceived">수신 카운트</param>

        public UDPHeader(byte[] sourceByteArray, int countReceived)

        {

            MemoryStream memoryStream = new MemoryStream(sourceByteArray, 0, countReceived);

            BinaryReader binaryReader = new BinaryReader(memoryStream);

 

            this.sourcePort      = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

            this.destinationPort = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

            this.length          = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

            this.checksum        = IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

 

            Array.Copy(sourceByteArray, 8, dataByteArray, 0, countReceived - 8);

        }

 

        #endregion

    }

}

 

 

MainForm.cs

 

 

using System;

using System.Net;

using System.Net.Sockets;

using System.Windows.Forms;

 

namespace TestProject

{

    /// <summary>

    /// 메인 폼

    /// </summary>

    public partial class MainForm : Form

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 메인 소켓

        /// </summary>

        private Socket mainSocket;

 

        /// <summary>

        /// 데이터 바이트 배열

        /// </summary>

        private byte[] dataByteArray = new byte[4096];

 

        /// <summary>

        /// 캡처 계속 여부

        /// </summary>

        private bool continueCapturing = false;

 

        /// <summary>

        /// 패킷 번호

        /// </summary>

        private int packetNumber = 1;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainForm()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainForm()

        {

            InitializeComponent();

 

            #region 이벤트를 설정한다.

 

            Load                   += Form_Load;

            this.startButton.Click += startButton_Click;

            this.stopButton.Click  += stopButton_Click;

            this.listView.Click    += listView_Click;

 

            #endregion

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        //////////////////////////////////////////////////////////////////////////////// Event

 

        #region 폼 로드시 처리하기 - Form_Load(sender, e)

 

        /// <summary>

        /// 폼 로드시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void Form_Load(object sender, EventArgs e)

        {

            this.packetNumberComboBox.Text = "100";

            

            string ipAddressString = null;

 

            IPHostEntry ipHostEntry = Dns.GetHostEntry((Dns.GetHostName()));

 

            if(ipHostEntry.AddressList.Length > 0)

            {

                foreach(IPAddress ipAddress in ipHostEntry.AddressList)

                {

                    ipAddressString = ipAddress.ToString();

 

                    this.ipAddressComboBox.Items.Add(ipAddressString);

                }

            }       

        }

 

        #endregion

        #region 시작 버튼 클릭시 처리하기 - startButton_Click(sender, e)

 

        /// <summary>

        /// 시작 버튼 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void startButton_Click(object sender, EventArgs e)

        {

            if(this.ipAddressComboBox.Text == string.Empty)

            {

                MessageBox.Show

                (

                    this,

                    "캡처할 네트워크 인터페이스를 선택해 주시기 바랍니다.",

                    "INFORMATION",

                    MessageBoxButtons.OK,

                    MessageBoxIcon.Information

                );

 

                return;

            }

 

            try

            {

                if(!this.continueCapturing)

                {

                    this.startButton.Enabled = false;

                    this.stopButton.Enabled  = true;

 

                    this.continueCapturing = true;

 

                    this.mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

 

                    this.mainSocket.Bind(new IPEndPoint(IPAddress.Parse(this.ipAddressComboBox.Text), 0));

 

                    this.mainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

 

                    byte[] trueByteArray = new byte[4] { 1, 0, 0, 0 };

                    byte[] outByteArray  = new byte[4] { 1, 0, 0, 0 };

 

                    this.mainSocket.IOControl(IOControlCode.ReceiveAll, trueByteArray, outByteArray);

 

                    this.mainSocket.BeginReceive

                    (

                        this.dataByteArray,

                        0,

                        this.dataByteArray.Length,

                        SocketFlags.None,

                        new AsyncCallback(ReceiveCallback),

                        null

                    );

                }

            }

            catch(Exception exception)

            {

                MessageBox.Show

                (

                    this,

                    exception.Message,

                    "ERROR",

                    MessageBoxButtons.OK,

                    MessageBoxIcon.Error

                );

            }

        }

 

        #endregion

        #region 중단 버튼 클릭시 처리하기 - stopButton_Click(sender, e)

 

        /// <summary>

        /// 중단 버튼 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void stopButton_Click(object sender, EventArgs e)

        {

            this.startButton.Enabled = true;

            this.stopButton.Enabled  = false;

            this.continueCapturing   = false;

 

            this.mainSocket.Close();

        }

 

        #endregion

        #region 리스트 뷰 클릭시 처리하기 - listView_Click(sender, e)

 

        /// <summary>

        /// 리스트 뷰 클릭시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void listView_Click(object sender, EventArgs e)

        {

            this.treeView.Nodes.Clear();

 

            this.treeView.Nodes.Add(this.listView.SelectedItems[0].SubItems[6].Text);

 

            for(int n = 7 ; n < 19 ;n++ )

            {

                 this.treeView.Nodes[0].Nodes.Add(this.listView.SelectedItems[0].SubItems[n].Text);

            }

 

            if(this.listView.SelectedItems[0].SubItems[4].Text == "TCP")

            {

                this.treeView.Nodes.Add(this.listView.SelectedItems[0].SubItems[19].Text);

 

                for(int n = 20; n < 28; n++)

                {

                    this.treeView.Nodes[1].Nodes.Add(this.listView.SelectedItems[0].SubItems[n].Text);

                }

            }

            else if(this.listView.SelectedItems[0].SubItems[4].Text == "UDP")

            {

                this.treeView.Nodes.Add(this.listView.SelectedItems[0].SubItems[19].Text);

 

                for(int n = 20; n < 24; n++)

                {

                    this.treeView.Nodes[1].Nodes.Add(this.listView.SelectedItems[0].SubItems[n].Text);

                }

            }

 

            this.treeView.ExpandAll();

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////// Function

 

        #region IP 항목 배열 구하기 - GetIPItemArray(ipHeader, protocolType)

 

        /// <summary>

        /// IP 항목 배열 구하기

        /// </summary>

        /// <param name="ipHeader">IP 헤더</param>

        /// <param name="protocolType">프로토콜 타입</param>

        /// <returns>IP 항목 배열</returns>

        private string[] GetIPItemArray(IPHeader ipHeader, string protocolType)

        {

            string[] stringArray = new string[]

            {

                "IP",

                "Ver : "                    + ipHeader.Version,

                "Header Length : "          + ipHeader.HeaderLength,

                "Differntiated Services : " + ipHeader.DifferentiatedServices,

                "Total Length : "           + ipHeader.TotalLength,

                "Identification : "         + ipHeader.Identification,

                "Flags : "                  + ipHeader.Flags,

                "Fragmentation Offset : "   + ipHeader.FragmentationOffset,

                "Time to live : "           + ipHeader.TTL,

                "Protocol : "               + protocolType,

                "Checksum : "               + ipHeader.Checksum,

                "Source : "                 + ipHeader.SourceAddress.ToString(),

                "Destination : "            + ipHeader.DestinationAddress.ToString()

            };

 

            return stringArray;

        }

 

        #endregion

        #region TCP 항목 배열 구하기 - GetTCPItemArray(tcpHeader)

 

        /// <summary>

        /// TCP 항목 배열 구하기

        /// </summary>

        /// <param name="tcpHeader">TCP 헤더</param>

        /// <returns>TCP 항목 배열</returns>

        private string[] GetTCPItemArray(TCPHeader tcpHeader)

        {

            string acknowledgement = null;

 

            if(tcpHeader.AcknowledgementNumber != string.Empty)

            {

                acknowledgement = "Acknowledgement Number : " + tcpHeader.AcknowledgementNumber;

            }

            else

            {

                acknowledgement =  "Acknowledgement Number : ";

            }

 

            string[] stringArray = new string[]

            {

                "TCP",

                "Source Port : "      + tcpHeader.SourcePort,

                "Destination Port : " + tcpHeader.DestinationPort,

                "Sequence Number : "  + tcpHeader.SequenceNumber,

                acknowledgement,

                "Header Length : "    + tcpHeader.HeaderLength,

                "Flags : "            + tcpHeader.Flags,

                "Window Size : "      + tcpHeader.WindowSize,

                "Checksum : "         + tcpHeader.Checksum};

 

            return stringArray;

        }

 

        #endregion

        #region UDP 항목 배열 구하기 - GetUDPItemArray(udpHeader)

 

        /// <summary>

        /// UDP 항목 배열 구하기

        /// </summary>

        /// <param name="udpHeader">UDP 헤더</param>

        /// <returns>UDP 항목 배열</returns>

        private string[] GetUDPItemArray(UDPHeader udpHeader)

        {

            string[] stringArray = new string[]

            {

                "UDP",

                "Source Port : "      + udpHeader.SourcePort,

                "Destination Port : " + udpHeader.DestinationPort,

                "Length : "           + udpHeader.Length,

                "Checksum : "         + udpHeader.Checksum

            };

 

            return stringArray;

        }

 

        #endregion

 

        #region 데이터 처리하기 - ProcessData(sourceByteArray, countReceived)

 

        /// <summary>

        /// 데이터 처리하기

        /// </summary>

        /// <param name="sourceByteArray">소스 바이트 배열</param>

        /// <param name="countReceived">수신 카운트</param>

        private void ProcessData(byte[] sourceByteArray, int countReceived)

        {

            if(this.packetNumber == Convert.ToInt32(this.packetNumberComboBox.Text))

            {

                this.packetNumber = 1;

 

                this.listView.Items.Clear();

            }

 

            IPHeader ipHeader = new IPHeader(sourceByteArray, countReceived);

 

            string[] baseItemArray = new string[]

            {

                this.packetNumber.ToString(),

                DateTime.Now.ToString(),

                ipHeader.SourceAddress.ToString(),

                ipHeader.DestinationAddress.ToString(),

                ipHeader.ProtocolType.ToString(),

                ipHeader.TotalLength

            };

 

            string[] ipItemArray = GetIPItemArray(ipHeader, ipHeader.ProtocolType.ToString());

 

            string[] mergeIPItemArray = new string[baseItemArray.Length + ipItemArray.Length];

 

            Array.Copy(baseItemArray, 0, mergeIPItemArray, 0, baseItemArray.Length);

 

            Array.Copy(ipItemArray, 0, mergeIPItemArray, baseItemArray.Length, ipItemArray.Length);

 

            string[] mergeTCPItemArray = null;

            string[] mergeUDPItemArray = null;

            string[] allItemArray      = null;

 

            switch(ipHeader.ProtocolType)

            {

                case Protocol.TCP :

 

                    TCPHeader tcpHeader = new TCPHeader(ipHeader.DataByteArray, ipHeader.MessageLength);

 

                    mergeTCPItemArray = GetTCPItemArray(tcpHeader);

 

                    allItemArray = new string[mergeIPItemArray.Length + mergeTCPItemArray.Length];

 

                    Array.Copy(mergeIPItemArray, 0, allItemArray, 0, mergeIPItemArray.Length);

 

                    Array.Copy(mergeTCPItemArray, 0, allItemArray, mergeIPItemArray.Length, mergeTCPItemArray.Length);

 

                    break;

 

                case Protocol.UDP :

 

                    UDPHeader udpHeader = new UDPHeader(ipHeader.DataByteArray, (int)ipHeader.MessageLength);

 

                    mergeUDPItemArray = GetUDPItemArray(udpHeader);

 

                    allItemArray = new string[mergeIPItemArray.Length + mergeUDPItemArray.Length];

 

                    Array.Copy(mergeIPItemArray, 0, allItemArray, 0, mergeIPItemArray.Length);

 

                    Array.Copy(mergeUDPItemArray, 0, allItemArray, mergeIPItemArray.Length, mergeUDPItemArray.Length);

 

                    break;

 

                case Protocol.UNKNOWN :

 

                    allItemArray = mergeIPItemArray;

 

                    break;

            }

 

            ListViewItem listViewItem = new ListViewItem(allItemArray);

 

            this.listView.Items.Add(listViewItem);

 

            this.packetNumber++;

        }

 

        #endregion

        #region 수신 콜백 처리하기 - ReceiveCallback(asyncResult)

 

        /// <summary>

        /// 수신 콜백 처리하기

        /// </summary>

        /// <param name="asyncResult">비동기 결과</param>

        private void ReceiveCallback(IAsyncResult asyncResult)

        {

            try

            {

                int countReceived = this.mainSocket.EndReceive(asyncResult);

 

                ProcessData(this.dataByteArray, countReceived);

 

                if(this.continueCapturing)

                {

                    this.dataByteArray = new byte[4096];

 

                    this.mainSocket.BeginReceive

                    (

                        this.dataByteArray,

                        0,

                        this.dataByteArray.Length,

                        SocketFlags.None,

                        new AsyncCallback(ReceiveCallback),

                        null

                    );

                }

            }

            catch(ObjectDisposedException)

            {

            }

            catch(Exception exception)

            {

                MessageBox.Show

                (

                    this,

                    exception.Message,

                    "ERROR",

                    MessageBoxButtons.OK,

                    MessageBoxIcon.Error

                );

            }

        }

 

        #endregion

    }

}

 

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

Posted by 사용자 icodebroker

댓글을 달아 주세요