블로그 이미지
따시쿵

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Notice

2015. 2. 25. 17:31 C# with UDP/IP

브로드캐스트는 같은 물리적 네트워크 상에 있는 받을 준비가 되어 있는 모든 컴퓨터에게 메시지를 전송하는 기법입니다. 기본적으로 라우터나 게이트웨이는 BROADCAST 메시지를 전달하지 않습니다.


브로드캐스트의 또 다른 제약사항은 인터페이스의 최대 전송 단위(maximum transmission unit, MTU)를 넘지 않는다는 겁니다. 기본적으로 브로드캐스트 패킷은 최대 전송 단위를 초과할 수 없습니다.

예를 들어 1460 (1500 - 20 (IP Header) - 20 (UDP Header)) 과 같습니다.


브로드캐스트 주소는 255.255.255.255 이거나 network broadcast address 입니다.

(예전의 브로드캐스트 주소인 0.0.0.0 은 현재는 네트워크 주소로 사용되고 있습니다.

예를 들어, 당신의 컴퓨터 주소가 192.168.20.0 이고 넷마스크가 255.255.255.0 이라면, 브로드캐스트 주소는 192.168.20.255 입니다. (192.168.20.0 might work for backward compatibility) 


당신의 IP address, netmask를 알고 있다면 다음의 공식을 이용해서 산출할 수 있습니다.

Your Broadcast address is: < IP Address > | ( ˜ Netmask ) 


이론적으로 브로드캐스트에 대한 이해를 돕기 위해서는 아래의 사이트를 참조하시기 바랍니다.

Internetwork Design Guide -- UDP Broadcast Flooding

Broadcasting and Multicasting

UDP 통신 시 브로드캐스트 IP 셋팅하기



브로드캐스트시 IP 셋팅 방법은 아래와 같습니다.


IP 주소의 서브넷 부분을 제외한 호스트 자리를 2진수 1로 채운 것을 말합니다.


1.

제품의 IP주소가 공장 초기 값인 10.1.0.1 이고 서브넷 마스크가 255.0.0.0 이라고 한다면,

네트워크 자리는 10. 까지이며 호스트 주소가 1.0.1 이 부분이 서브넷 마스크가 0.0.0 이기 때문에 

그 부분의 2진수를 1로 다 채우게 되면 10.255.255.255가 되겠습니다.

http://blog.sollae.co.kr/?p=691


2.

제품 IP주소가 192.168.0.100 이고, 서브넷 마스크가 255.255.255.0인 경우는 브로드캐스트 IP가 무엇이 될까요

바로 192.168.0.255입니다. 서브넷 마스크가 나타내는 네트워크 자리는 192.168.0.이며 호스트 자리는 100입니다.

호스트자리를 전체 1로 다 채우면 255가 되겠습니다.

http://blog.sollae.co.kr/?p=691


3.

172 대역을 살펴보겠습니다.

제품 IP주소가 172.16.0.100 이고 서브넷 마스크가 255.255.254.0인 경우의 브로드캐스트 IP는 바로 172.16.1.255입니다.

http://blog.sollae.co.kr/?p=691


4.

ip 주소가 255.255.255.255 를 사용합니다. 같은 물리적 네트워크상의 모든 컴퓨터에게 메시지를 전송합니다.

http://www.tack.ch/multicast/broadcast.shtml



프로그램 설명


sender 가 UdpClient 를 생성하여 broadcast IP 인 255.255.255.255 주소로 메시지를 전송하고, receiver 에서는 메시지 받는 루틴을 만들어서 sender 가 전송한 메시지를 받아서 화면에 보여 줍니다.



실행 후






메시지 전송 후






프로그램 작성 순서


1. sender 프로그램


UDPer class define

    class UDPer
    {
        private const int PORT_NUMBER = 15000;

        public void Send(string message)
        {
            UdpClient client = new UdpClient();
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT_NUMBER);
            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            byte[] bytes = Encoding.UTF8.GetBytes(message);
            client.Send(bytes, bytes.Length, ip);
            client.Close();

            if (OnSendMessage != null)
                OnSendMessage(message);
        }

        public delegate void SendMessageHandler(string message);
        public event SendMessageHandler OnSendMessage;
    }


Windows Form define

        UDPer udper = null;
        public SendForm()
        {
            InitializeComponent();

            udper = new UDPer();
            udper.OnSendMessage += new UDPer.SendMessageHandler(udper_OnSendMessage);
        }

        void udper_OnSendMessage(string message)
        {
            Trace.WriteLine(string.Format("sent messge : {0}", message));
            lblResult.Text = message;
        }

        private void button1_Click(object sender, EventArgs e)
        {            
            udper.Send(textBox1.Text);
        }


2. receiver 프로그램


UDPer class define

    class UDPer
    {
        private const int PORT_NUMBER = 15000;

        private UdpClient udp = null;
        IAsyncResult ar_ = null;
        
        public void Start()
        {
            if (udp != null)
            {
                throw new Exception("Alread started, stop first");                
            }

            udp = new UdpClient();

            IPEndPoint localEp = new IPEndPoint(IPAddress.Any, PORT_NUMBER);

            udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udp.ExclusiveAddressUse = false;
            udp.Client.Bind(localEp);

            StartListening();
        }

        public void Stop()
        {
            try
            {
                if (udp != null)
                {
                    udp.Close();
                    udp = null;
                }
            }
            catch { }
        }

        private void StartListening()
        {
            ar_ = udp.BeginReceive(Receive, new object());
        }

        private void Receive(IAsyncResult ar)
        {
            try
            { 
                if (udp != null)
                { 
                    IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT_NUMBER);
                    byte[] bytes = udp.EndReceive(ar, ref ip);
                    string message = Encoding.UTF8.GetString(bytes);
                    StartListening();

                    if (OnReceiveMessage != null)
                        OnReceiveMessage(message);
                }
            }
            catch(SocketException se)
            {
                Trace.WriteLine(string.Format("SocketException : {0}", se.Message));
            }
            catch(Exception ex)
            {
                Trace.WriteLine(string.Format("Exception : {0}", ex.Message));
            }
        }

        public delegate void ReceiveMessageHandler(string message);
        public event ReceiveMessageHandler OnReceiveMessage;

    }


Windows Form define

        UDPer udper = null;
        bool isBtnCommandEnabled = true;
        public ReceiveForm()
        {
            InitializeComponent();

            udper = new UDPer();
            udper.OnReceiveMessage += new UDPer.ReceiveMessageHandler(udper_OnReceiveMessage);

        }

        protected override void OnClosed(EventArgs e)
        {
            if (udper != null)
                udper.Stop();

            base.OnClosed(e);
        }

        void udper_OnReceiveMessage(string message)
        {
            Trace.WriteLine(string.Format("received message : {0}", message));
            Invoke((MethodInvoker)delegate
            {
                lblReceive.Text = message;
            });
        }

        private void btnCommand_Click(object sender, EventArgs e)
        {
            if (isBtnCommandEnabled)
            { 
                udper.Start();
                UpdateUI(isBtnCommandEnabled);
                isBtnCommandEnabled = false;                
            }
            else
            {
                udper.Stop();                
                UpdateUI(isBtnCommandEnabled);
                isBtnCommandEnabled = true;
            }
        }

        private void UpdateUI(bool isBool)
        {
            if (isBool)
            {
                this.btnCommand.Text = "Stop the UDP Client";
                this.btnCommand.ForeColor = Color.White;
                this.btnCommand.BackColor = Color.Orange;
            }
            else
            {
                this.btnCommand.Text = "Stop the UDP Client";
                this.btnCommand.ForeColor = SystemColors.ControlText;
                this.btnCommand.BackColor = SystemColors.Control;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (udper != null)
                udper.Stop();

            this.Close();
        }


posted by 따시쿵
2015. 2. 12. 15:57 C# with UDP/IP

udp multicast 는 sender가 receiver 에게 데이타를 단방향 통신으로 전달하는 기술 기법입니다.


multicast 구현시 고려할 사항


▷ IP multicast 에서 사용할 아이피를 적당하게 잘 선택해야 합니다. 

   선택한 아이피로 멀티캐스트그룹을 만들어야 하므로 다른 시스템에서 사용하지 않는 아이피를 사용

   합니다.

   

   사용할 아이피는 IANA 정보에 따라서 239.0.0.0 와 239.255.255.255 사이의 아이피를 선택합니다.

   MComms TV 에도 정보가 나와 있으니 참조하면 됩니다.


▷ 시스템에서 사용하지 않는 포트를 선택합니다.

   Windows Vista, 7, 2008 는 포트 번호 49152 와 65535, 예전 윈도즈는 1025 와 5000 그리고 Linux

   는 32768 와 61000 번호를 선택합니다.

   

   자세한 정보는 여기에 나와 있습니다. MComms TV 



프로그램 설명


sender 가 특정 아이피로 멀티캐스트그룹을 만들고, 그룹에 참가하는 receiver 에게 루프를 돌면서 메시지를 전송한 것입니다.



실행 후


메시지 전송 후


프로그램 작성 순서


1. 공통 라이브러리


using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;


2. Sender 프로그램


        static void Main(string[] args)
        {
            UdpClient udpclient = new UdpClient();

            IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
            udpclient.JoinMulticastGroup(multicastaddress);
            IPEndPoint remoteEP = new IPEndPoint(multicastaddress, 2222);

            byte[] buffer = null;

            Console.WriteLine("Press ENTER to start sending message");
            Console.ReadLine();

            for (int i = 0; i <= 8000; i++)
            {
                buffer = Encoding.Unicode.GetBytes(i.ToString());
                udpclient.Send(buffer, buffer.Length, remoteEP);
                Console.WriteLine("Sent : {0}", i.ToString());
            }

            buffer = Encoding.Unicode.GetBytes("quit");
            udpclient.Send(buffer, buffer.Length, remoteEP);

            udpclient.Close();

            Console.WriteLine("All Done! Press ENTER to quit.");
            Console.ReadLine();
        }


3. Receiver 프로그램


        static void Main(string[] args)
        {
            UdpClient client = new UdpClient();

            client.ExclusiveAddressUse = false;
            IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 2222);

            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            client.ExclusiveAddressUse = false;

            client.Client.Bind(localEp);

            IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
            client.JoinMulticastGroup(multicastaddress);

            Console.WriteLine("Listening this will quit");

            while(true)
            {
                byte[] data = client.Receive(ref localEp);
                string strData = Encoding.Unicode.GetString(data);
                Console.WriteLine("received data : {0}", strData);

                if (strData == "quit")
                    break;
            }

            Console.WriteLine("quit the program to ENTER");
            Console.ReadLine();
        }
posted by 따시쿵
2015. 2. 2. 16:48 C# with UDP/IP

프로그램 설명


udp 클라이언트/서버 예제입니다.


UdpClient 클래스는 전송 및 동기 블록 모드 비 연결 UDP 데이터 그램 을 수신하기위한 간단한 방법을 제공합니다. UDP 는 비 연결 전송 프로토콜 이기 때문에, 전송 및 데이터를 수신 하기 전에 원격 호스트 연결을 설정할 필요가 없습니다. 


다음의 두 가지 방법 중 하나를기본 원격 호스트를 확립 하는 옵션 을 가질 것 :


1. 원격 호스트 이름 및 매개 변수로 포트 번호를 사용하여 UdpClient 클래스의 인스턴스를 만듭니다.

2. UdpClient 클래스의 인스턴스를 생성 한 다음 연결 메소드를 호출합니다.


ReceiveFrom method 의 IPEndPoint 을 이용해서 전송하는 호스트의 정보를 알 수 있습니다.


실행 후


메시지 전송 후





프로그램 작성 순서


1. 소켓과 관련한 네임스페이스를 서버/클라이언트 모두에 포함 시킵니다.


using System.Net;
using System.Net.Sockets;


2. 서버 프로그램


        static void Main(string[] args)
        {
            int recv = 0;
            byte[] data = new byte[1024];

            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 9050);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            server.Bind(ep);

            Console.WriteLine("Waiting for a client...");

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint remoteEP = (EndPoint)sender;

            recv = server.ReceiveFrom(data, ref remoteEP);
            
            Console.WriteLine("[first] Message received from {0}", remoteEP.ToString());
            Console.WriteLine("[first] received data : {0}", Encoding.UTF8.GetString(data, 0, recv));

            string welcome = "Welcome to udp server";
            data = Encoding.UTF8.GetBytes(welcome);
            server.SendTo(data, remoteEP);

            while(true)
            {
                data = new byte[1024];
                recv = server.ReceiveFrom(data, ref remoteEP);
                string recvData = Encoding.UTF8.GetString(data, 0, recv);
                Console.WriteLine("received data : {0}", recvData);

                server.SendTo(Encoding.UTF8.GetBytes(recvData), remoteEP);
                Console.WriteLine("send data : {0}", Encoding.UTF8.GetString(data, 0, recv));
                Console.WriteLine("");
            }

            server.Close();
        }


3. 클라이언트 프로그램


        static void Main(string[] args)
        {
            int recv = 0;
            byte[] data = new byte[1024];
            string input, stringData;

            IPEndPoint serverEP = new IPEndPoint(IPAddress.Parse("192.168.0.12"), 9050);

            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint remoteEP = (EndPoint)sender;

            string welcome = "hello, udp server?";
            data = Encoding.UTF8.GetBytes(welcome);
            client.SendTo(data, data.Length, SocketFlags.None, serverEP);

            data = new byte[1024];
            recv = client.ReceiveFrom(data, ref remoteEP);

            Console.WriteLine("[first] Message received from {0}", remoteEP.ToString());
            stringData = Encoding.UTF8.GetString(data, 0, recv);
            Console.WriteLine(stringData);

            while (true)
            {
                Console.Write("send data : ");
                input = Console.ReadLine();
                if (input == "exit")
                    break;

                data = Encoding.UTF8.GetBytes(input);
                client.SendTo(data, data.Length, SocketFlags.None, serverEP);

                recv = client.ReceiveFrom(data, ref remoteEP);
                stringData = Encoding.UTF8.GetString(data);
                Console.WriteLine("received data : {0}", stringData);
            }

            Console.WriteLine("Stopping client");
            client.Close();
        }


'C# with UDP/IP' 카테고리의 다른 글

[Program C#]Broadcast  (0) 2015.02.25
[Program C#]UDP Multicast  (0) 2015.02.12
[Program C#]UDP 통신 - 기본(UdpClient) - 콘솔 버전  (0) 2015.02.02
TCP & UDP 비교  (0) 2015.02.02
posted by 따시쿵
2015. 2. 2. 09:12 C# with UDP/IP

프로그램 설명


udp 클라이언트/서버 예제입니다.


UdpClient 클래스는 전송 및 동기 블록 모드 비 연결 UDP 데이터 그램 을 수신하기위한 간단한 방법을 제공합니다. UDP 는 비 연결 전송 프로토콜 이기 때문에, 전송 및 데이터를 수신 하기 전에 원격 호스트 연결을 설정할 필요가 없습니다. 


다음의 두 가지 방법 중 하나를기본 원격 호스트를 확립 하는 옵션 을 가질 것 :


1. 원격 호스트 이름 및 매개 변수로 포트 번호를 사용하여 UdpClient 클래스의 인스턴스를 만듭니다.

2. UdpClient 클래스의 인스턴스를 생성 한 다음 연결 메소드를 호출합니다.


Receive method 의 IPEndPoint 을 이용해서 전송하는 호스트의 정보를 알 수 있습니다.


실행 후


메시지 전송 후



프로그램 작성 순서


1. 소켓과 관련한 네임스페이스를 서버/클라이언트 모두에 포함 시킵니다.


using System.Net;
using System.Net.Sockets;


2. 서버 프로그램


            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
            UdpClient server = new UdpClient(ipep);

            Console.WriteLine("Waiting for a client....");

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            data = server.Receive(ref sender);

            Console.WriteLine("Message received from {0}", sender.ToString());
            Console.WriteLine("received data : {0}", Encoding.UTF8.GetString(data, 0, data.Length));

            string welcome = "Welcome to my udp server";
            data = Encoding.UTF8.GetBytes(welcome);
            server.Send(data, data.Length, sender);

            while(true)
            {
                data = server.Receive(ref sender);
                Console.WriteLine("received data : {0}", Encoding.UTF8.GetString(data, 0, data.Length));

                server.Send(data, data.Length, sender);
                Console.WriteLine("send data : {0}", Encoding.UTF8.GetString(data, 0, data.Length));
            }

            server.Close();


3. 클라이언트 프로그램


            byte[] data = new byte[1024];
            string input, stringData;
            UdpClient client = new UdpClient("192.168.0.12", 9050);

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            string welcome = "hello, udp server?";
            data = Encoding.UTF8.GetBytes(welcome);
            client.Send(data, data.Length);

            data = client.Receive(ref sender);

            Console.WriteLine("Message received from {0}", sender.ToString());
            stringData = Encoding.UTF8.GetString(data, 0, data.Length);
            Console.WriteLine(stringData);

            while(true)
            {
                Console.Write("send data : ");
                input = Console.ReadLine();
                if (input == "exit")
                    break;

                data = Encoding.UTF8.GetBytes(input);
                client.Send(data, data.Length);
                data = client.Receive(ref sender);
                stringData = Encoding.UTF8.GetString(data);
                Console.WriteLine("received data : {0}", stringData);
            }

            client.Close();
            Console.WriteLine("Stopping clinet");
            


'C# with UDP/IP' 카테고리의 다른 글

[Program C#]Broadcast  (0) 2015.02.25
[Program C#]UDP Multicast  (0) 2015.02.12
[Program C#]UDP 통신 - 기본(Socket) - 콘솔 버전  (1) 2015.02.02
TCP & UDP 비교  (0) 2015.02.02
posted by 따시쿵
2015. 2. 2. 09:11 C# with UDP/IP






posted by 따시쿵
prev 1 next