SendTo() public method

public SendTo ( byte buffer, EndPoint remoteEP ) : int
buffer byte
remoteEP EndPoint
return int
Example #1
0
 static void Main(string[] args)
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9000);
     s.Bind(iep);
     EndPoint remote = (EndPoint)iep;
     byte[] data = new byte[1024];
     int k = s.ReceiveFrom(data, ref remote);
     Console.WriteLine("Loi chao tu Client:{0}",Encoding.ASCII.GetString(data,0,k));
     data = new byte[1024];
     data = Encoding.ASCII.GetBytes("Chao Client ket noi");
     s.SendTo(data, remote);
     while (true)
     {
         data = new byte[1024];
         string st;
         k=s.ReceiveFrom(data, ref remote);
         st = Encoding.ASCII.GetString(data, 0, k);
         Console.WriteLine("Du lieu tu Client Gui la:{0}", st);
         if (st.ToUpper().Equals("QUIT"))
             break;
         st = st.ToUpper();
         data = new byte[1024];
         data = Encoding.ASCII.GetBytes(st);
         s.SendTo(data, remote);
     }
     s.Close();
 }
Example #2
0
        private static bool Discover() {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            byte[] data = Encoding.ASCII.GetBytes(req);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, 1900);
            byte[] buffer = new byte[0x1000];

            DateTime start = DateTime.Now;
            try {
                do {
                    s.SendTo(data, ipe);
                    s.SendTo(data, ipe);
                    s.SendTo(data, ipe);

                    int length = 0;
                    do {
                        length = s.Receive(buffer);

                        string resp = Encoding.ASCII.GetString(buffer, 0, length);
                        if (resp.Contains("upnp:rootdevice")) {
                            resp = resp.Substring(resp.ToLower().IndexOf("location:") + 9);
                            resp = resp.Substring(0, resp.IndexOf("\r")).Trim();
                            if (!string.IsNullOrEmpty(_serviceUrl = GetServiceUrl(resp))) {
                                _descUrl = resp;
                                return true;
                            }
                        }
                    } while (length > 0);
                } while (start.Subtract(DateTime.Now) < _timeout);
                return false;
            }
            catch {
                return false;
            }
        }
Example #3
0
 static void Main(string[] args)
 {
     byte[] data = new byte[1024];
     string input, stringData;
     IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("38.98.173.2"), 58642);
     //IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 58642);
     Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     string welcome = "Hello, are you there?";
     data = Encoding.ASCII.GetBytes(welcome);
     server.SendTo(data, data.Length, SocketFlags.None, ipep);
     IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
     EndPoint Remote = (EndPoint)sender;
     data = new byte[1024];
     int recv = server.ReceiveFrom(data, ref Remote);
     Console.WriteLine("Message received from {0}:", Remote.ToString());
     Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
     while (true)
     {
         input = Console.ReadLine();
         if (input == "exit")
             break;
         server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
         data = new byte[1024];
         recv = server.ReceiveFrom(data, ref Remote);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
     }
     Console.WriteLine("Stopping client");
     server.Close();
 }
Example #4
0
 static void Main(string[] args)
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
     string st = "Chao Server";
     byte[] data = new byte[1024];
     data = Encoding.ASCII.GetBytes(st);
     s.SendTo(data, iep);
     EndPoint remote=(EndPoint)iep;
     data = new byte[1024];
     int k=s.ReceiveFrom(data,ref remote);
     Console.WriteLine("Loi chao tu Server:{0}", Encoding.ASCII.GetString(data, 0, k));
     while (true)
     {
         Console.Write("Nhap du lieu gui len Server:");
         string st1 = Console.ReadLine();
         byte[] dl = new byte[1024];
         dl = Encoding.ASCII.GetBytes(st1);
         s.SendTo(dl, remote);
         if (st1.ToUpper().Equals("QUIT"))
             break;
         dl = new byte[1024];
         int k1=s.ReceiveFrom(dl, ref remote);
         Console.WriteLine("Du lieu tu Server la:{0}", Encoding.ASCII.GetString(dl, 0, k1));
     }
     s.Close();
 }
Example #5
0
File: UPnP.cs Project: JyBP/SupChat
        public static string Discover()
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            string req = "M-SEARCH * HTTP/1.1\r\n" +
            "HOST: 239.255.255.250:1900\r\n" +
            "ST:upnp:rootdevice\r\n" +
            "MAN:\"ssdp:discover\"\r\n" +
            "MX:3\r\n\r\n";
            byte[] data = Encoding.ASCII.GetBytes(req);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, 1900);
            byte[] buffer = new byte[0x1000];

            DateTime start = DateTime.Now;
            WriteLineInFile("debug.txt", ipe.Address.ToString() + ";" + ipe.AddressFamily.ToString() + ";" + ipe.Port.ToString());
            do
            {
                s.SendTo(data, ipe);
                s.SendTo(data, ipe);
                s.SendTo(data, ipe);

                WriteLineInFile("debug.txt", "Sended");

                int length = 0;
                do
                {
                    try
                    {
                        length = s.Receive(buffer);
                    }
                    catch (SocketException e)
                    {
                        WriteLineInFile("debug.txt", e.Message+" Error code: "+ e.ErrorCode);
                    }

                    WriteLineInFile("debug.txt", "lenght:" + length);
                    /*
                    string resp = Encoding.ASCII.GetString(buffer, 0, length).ToLower();
                    if (resp.Contains("upnp:rootdevice"))*/
                    string resp = Encoding.ASCII.GetString(buffer, 0, length);
                    if (resp.ToLower().Contains("upnp:rootdevice"))
                    {
                        resp = resp.Substring(resp.ToLower().IndexOf("location:") + 9);
                        resp = resp.Substring(0, resp.IndexOf("\r")).Trim();
                        if (!string.IsNullOrEmpty(_serviceUrl = GetServiceUrl(resp)))
                        {
                            _descUrl = resp;
                            return "_descUrl=" + _descUrl + "\n_serviceUrl=" + _serviceUrl;
                        }
                    }
                } while (length > 0 && start.Subtract(DateTime.Now) < _timeout);
            } while (start.Subtract(DateTime.Now) < _timeout);
            return "false";
        }
Example #6
0
        public BroadcastFinder()
        {
            Server = "";
            IPAddress[] a = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            string broadcastAddress = "";
            foreach (IPAddress t in a)
            {
                if (!t.ToString().Contains(":"))
                {
                    broadcastAddress = t.ToString();
                    break;
                }
            }
            Port = 2080;
            broadcastAddress = broadcastAddress.Substring(0, broadcastAddress.LastIndexOf('.')) + ".255";

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 61111);
            IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse(broadcastAddress), 61111);
            EndPoint ep = (EndPoint)iep;

            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            sock.ReceiveTimeout = 200;

            byte[] bs = Encoding.ASCII.GetBytes("Amleto client search");

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    sock.SendTo(bs, iep);
                    sock.SendTo(bs, iep2);

                    byte[] data = new byte[1024];
                    int res = sock.ReceiveFrom(data, ref ep);
                    string sres = Encoding.ASCII.GetString(data, 0, res);
                    string[] parts = sres.Split(' ');

                    if (parts[0] == "Amleto" && parts[1] == "server")
                    {
                        Server = parts[3];
                        Port = Convert.ToInt32(parts[4]);
                        break;
                    }
                }
                catch (Exception)
                {
                    // Don't log exception here as this is expected to fail if server isn't running
                }
            }
        }
Example #7
0
        public bool Discover()
        {
            Disconnect();

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            string req = "M-SEARCH * HTTP/1.1\r\n" +
            "HOST: 239.255.255.250:1900\r\n" +
            "ST:upnp:rootdevice\r\n" +
            "MAN:\"ssdp:discover\"\r\n" +
            "MX:3\r\n\r\n";
            byte[] data = Encoding.ASCII.GetBytes(req);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, 1900);
            byte[] buffer = new byte[0x1000];

            DateTime start = DateTime.Now;

            try
            {
                do
                {
                    _socket.SendTo(data, ipe);
                    _socket.SendTo(data, ipe);
                    _socket.SendTo(data, ipe);

                    int length = 0;
                    do
                    {
                        length = _socket.Receive(buffer);

                        string resp = Encoding.ASCII.GetString(buffer, 0, length).ToLower();
                        if (resp.Contains("upnp:rootdevice"))
                        {
                            resp = resp.Substring(resp.ToLower().IndexOf("location:") + 9);
                            resp = resp.Substring(0, resp.IndexOf("\r")).Trim();
                            if (!string.IsNullOrEmpty(_serviceUrl = GetServiceUrl(resp)))
                            {
                                _descUrl = resp;
                                return true;
                            }
                        }
                    } while (length > 0);
                } while (start.Subtract(DateTime.Now) < _timeout);
            }
            catch (Exception e)
            {
                Debug.Log("error: " + e.ToString());
            }

            return false;
        }
Example #8
0
        public void SendName(string name)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 8101);
            IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse(this.ip), 8101);

            string username =name ;
            byte[] data = Encoding.ASCII.GetBytes("*us*"+username);

            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            sock.SendTo(data, iep1);
            sock.SendTo(data, iep2);
            sock.Close();
        }
        static void sendBroadcastAnswer()
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
            IPEndPoint iep2 = new IPEndPoint(Internet.GetMaxBroadcast(), BroadcastSendPort);

            byte[] data = Encoding.ASCII.GetBytes(Internet.GetLocalIP().ToString());

            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            try { sock.SendTo(data, iep1); }
            catch { }
            try { sock.SendTo(data, iep2); }
            catch { }
            sock.Close();
        }
Example #10
0
        private void SendQuery2(IPAddress ipAddress, int port)
        {
            int timeout = 5000;

            if (ipAddress == null)
            {
                throw new ArgumentNullException();
            }

            //preparing the DNS query packet.
            byte[] QueryPacket = MakeQuery();

            //opening the UDP socket at DNS server
            IPAddress serverAddress = ipAddress;
            EndPoint  endPoint      = new IPEndPoint(serverAddress, port);
            SOCKET    socket        = new SOCKET(serverAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);

            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout);
            socket.SendTo(QueryPacket, endPoint);
            data = new byte[512];

            length = socket.ReceiveFrom(data, ref endPoint);

            //un pack the byte array & makes an array of resource record objects.
            ReadResponse();

            socket.Shutdown(SocketShutdown.Both);
        }
Example #11
0
 private void backgroundWorker1_DoWork(System.Object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     IPAddress targetIp = IPAddress.Parse(IP);
     //IP to send the packets to
     IPEndPoint target = new IPEndPoint(targetIp, Port);
     //Port to flood
     byte[] packet = new byte[1470];
     //Creates bytes
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     //Creates sockets
     while (true)
     {
         if (backgroundWorker1.CancellationPending == true)
         {
             return;
         }
         try
         {
             socket.SendTo(packet, target);
             //Sends packets
             i += 1;
         }
         catch (Exception ex)
         {
             //MessageBox(IP + " is not reachable at the moment! Please try again later.");
             Application.Exit();
             //Closes the application
         }
     }
 }
Example #12
0
        protected void SendTo(byte[] data, EndPoint endPoint)
        {
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            bool isTooBig = false;
            byte[] toSend;
            if (data.Length > _BufferSize)
            {
                toSend = new byte[_BufferSize];
                Array.Copy(data, toSend, _BufferSize);
                int length = data.Length - _BufferSize;
                Array.Copy(data, _BufferSize, data, 0, length);
                Array.Resize(ref data, length);
                isTooBig = true;

            }
            else
            {
                toSend = data;
            }

            sender.SendTo(toSend, endPoint);

            if (isTooBig)
            {
                SendTo(data, endPoint);
            }
        }
        private static void MobileServer()
        {
            int port = 1820;
            IPEndPoint remoteServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1819);

            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            try
            {
                socket.Bind(localEP);
                Console.WriteLine("手机模拟器启动了....");

                Console.WriteLine("请打开 http://localhost:8075/test.html");

                Console.WriteLine("请输入您看到的GUID码");

                string guid = Console.ReadLine();
                byte[] data = Encoding.UTF8.GetBytes(guid);

                socket.SendTo(data, data.Length, SocketFlags.None, remoteServer);
                Console.WriteLine("已经把GUID发送至手机通讯服务器");
                Console.ReadLine();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Example #14
0
        private void Form1_Load(object sender, EventArgs e)
        {
            int address_len, port_len;
            int offset = 0;
            IPAddress ia = IPAddress.Any;
            IPEndPoint ie = new IPEndPoint(ia, 8000);
            EndPoint iep = (EndPoint)ie;
            char[] send_data = new char[1024];

            Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //test.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.BlockSource, false);
            test.Bind(ie);
            //test.Listen(5);
            //Socket newSocket = test.Accept();
            byte[] data = new byte[1024];
            //newSocket.Receive(data);
            test.ReceiveFrom(data, ref iep);
            address_len = Convert.ToInt16(Encoding.ASCII.GetString(data).Substring(0,3));
            port_len = Convert.ToInt16(Encoding.ASCII.GetString(data).Substring(4+address_len,4));
            IPEndPoint ie2 = new IPEndPoint(IPAddress.Parse(Encoding.ASCII.GetString(data).Substring(4, address_len)), Convert.ToInt16(Encoding.ASCII.GetString(data).Substring(8 + address_len, port_len)));
            //IPEndPoint ie2 = new IPEndPoint(IPAddress.Loopback, 8001);
            EndPoint iep2 = (EndPoint)ie2;

            richTextBox1.Text += Encoding.ASCII.GetString(data).Substring(8+address_len+port_len);
            send_data = fillUDP.fillingUDP(out offset, Listen_port);
            test.SendTo(Encoding.ASCII.GetBytes(send_data), iep2);
            test.Close();
        }
Example #15
0
 private void button4_Click(object sender, EventArgs e)
 {
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
     socket.SendTo(System.Text.Encoding.Unicode.GetBytes(textBox2.Text), new IPEndPoint(IPAddress.Parse("10.2.21.255"), 100));
     socket.Shutdown(SocketShutdown.Send);
     socket.Close();
 }
Example #16
0
        static void Main(string[] args)
        {
            long i = 0;
            bool down = false;
            string message;

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPAddress broadcast = IPAddress.Parse("192.168.1.255");
            IPEndPoint ep = new IPEndPoint(broadcast, 12345);

            while (true)
            {
                message = i.ToString() + "," + (i + 1).ToString() + "," + (i + 2).ToString() + "," + (i + 3).ToString() + "," + (i + 4).ToString() + "," + (i + 5).ToString();
                byte[] sendbuf = Encoding.ASCII.GetBytes(message);

                s.SendTo(sendbuf, ep);

                Thread.Sleep(10);
                if (!down)
                    i += 3;
                else
                    i -= 3;

                if (!down && i >= 400)
                    down = true;
                else if (down && i <= 0)
                    down = false;
            }
        }
Example #17
0
 public void sendPacket(Packet packet)
 {
     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     byte[] data = Deconstruct(packet);
     IPEndPoint endPoint = new IPEndPoint(hostIP, 11000);
     socket.SendTo(data, endPoint);
 }
        public string SendMsgWithReceive(string ipaddress, int port, string sendData)
        {
            try
            {
                byte[] bytesSent;
                byte[] buffer = new byte[1024];
                bytesSent = Encoding.UTF8.GetBytes(sendData);
                EndPoint ipe = new IPEndPoint(IPAddress.Parse(ipaddress), port);
                Socket clientSocket = new Socket(SocketType.Dgram, ProtocolType.Udp);

                clientSocket.SendTo(bytesSent, bytesSent.Length, SocketFlags.None, ipe);

                int receiveCount = clientSocket.ReceiveFrom(buffer, SocketFlags.None, ref ipe);

                string data = Encoding.UTF8.GetString(buffer, 0, receiveCount);

                clientSocket.Close();
                clientSocket = null;

                return data;
            }
            catch (Exception ex)
            {
            }
            return null;
        }
Example #19
0
        private static FoundServerInformation BroadcastPing(IPAddress broadcastAddress, int port) {
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) {
                SendTimeout = OptionLanSocketTimeout,
                ReceiveTimeout = OptionLanSocketTimeout,
                Blocking = false
            }) {
                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                var buffer = new byte[3];
                try {
                    socket.SendTo(BitConverter.GetBytes(200), SocketFlags.DontRoute, new IPEndPoint(broadcastAddress, port));
                    if (socket.Poll(OptionLanPollTimeout * 1000, SelectMode.SelectRead)) {
                        socket.ReceiveFrom(buffer, ref remoteEndPoint);
                    }
                } catch (SocketException) {
                    return null;
                }

                if (buffer[0] != 200 || buffer[1] + buffer[2] <= 0) {
                    return null;
                }

                var foundServer = remoteEndPoint as IPEndPoint;
                if (foundServer == null) {
                    return null;
                }

                return new FoundServerInformation {
                    Ip = foundServer.Address.ToString(),
                    Port = BitConverter.ToInt16(buffer, 1)
                };
            }
        }
Example #20
0
        public void SendMsg()
        {
            using ( Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ) )
            {

                StringBuilder sb = new StringBuilder();

                string sessionID = Guid.NewGuid().ToString();

                for ( int i = 0; i < 1; i++ )
                {
                    sb.Append( "$" ); //Protocol Header
                    sb.Append( "005" ); //Operation length
                    sb.Append( "LogIn" ); //Operation name

                    string command = sb.ToString();

                    Player user = new Player( "test", "123qqq" );
                    byte [] Object = Utils.ObjectToBytes( user );

                    MyRequestInfo Info = new MyRequestInfo( command, sessionID, Object );

                    socket.SendTo( Info.ToData(), serverAddress );

                    //socket.ReceiveTimeout = 1000;
                    string[] res = m_Encoding.GetString( ReceiveMessage( socket, serverAddress ).ToArray() ).Split( ' ' );

                }
            }
        }
Example #21
0
        public void SendServerPing()
        {
            StartListeningForServerPingBacks();

            // Create a socket udp ipv4 socket
            using (var sock = new Socket(AddressFamily.Unspecified, SocketType.Dgram, ProtocolType.Udp))
            {
                // Create our endpoint using the IP broadcast address and our port
            //                var endPoint = new IPEndPoint(IPAddress.Broadcast, ServiceInfo.UDPPort);
            //                var endPoint = new IPEndPoint(IPAddress.Parse("192.168.1.255"), ServiceInfo.UDPPort);
                var endPoint = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 5353);

                // Serialize our ping "payload"
                //var data = Helpers.SerializeObject(new ServiceClientInfo(Helpers.GetCurrentIPAddress().ToString(), PORT));
                var data = Encoding.UTF8.GetBytes(String.Format("{0}:{1}", Helpers.GetCurrentIPAddress(), CLIENT_PORT));

                // Tell our socket to reuse the address so we can send and receive on the same port.
                sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                // Tell the socket we want to broadcast - if we don't do this it won't let us send.
                sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);

                // Send the ping and close the socket.
                sock.SendTo(data, endPoint);
                sock.Close();
            }
        }
Example #22
0
        public MainWindow()
        {
            InitializeComponent();
            var r = new Random();
            _port = r.Next(1500, 2000);
            _id = Guid.NewGuid();

            _sessions = new Dictionary<IPEndPoint, Tuple<Peer, PascalMessageHandler>>();
            _listener = new TcpListener(_port);
            _comunicationManager = new CommunicationManager(_listener);
            _comunicationManager.ConnectionClosed += ChatOnMemberDisconnected;
            _comunicationManager.PeerConnected += ChatOnMemberConnected;
            _comunicationManager.ConnectionFailed += ChatOnMemberConnectionFailure;
            _comunicationManager.PeerDataReceived += OnPeerDataReceived;

            _listener.Start();

            _discovery = new UdpListener(3000);
            _discovery.UdpPacketReceived += DiscoveryOnUdpPacketReceived;
            _discovery.Start();

            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                socket.EnableBroadcast = true;
                var group = new IPEndPoint(IPAddress.Broadcast, 3000);
                var hi = Encoding.ASCII.GetBytes("Hi Peer2Net node here:" + _id + ":127.0.0.1:" + _port);
                socket.SendTo(hi, group);
                socket.Close();
            }
        }
 public static int uLink_DoNetworkSend(System.Net.Sockets.Socket socket, byte[] buffer, int length, EndPoint ip)
 {
     try
     {
         int result = length;
         if (ProtectLoader.Netlog && length > 0)
         {
             Debug.Log(string.Concat(new object[]
             {
                 "Network.Send(",
                 ip,
                 ").Packet(",
                 length,
                 "): ",
                 BitConverter.ToString(buffer, 0, length).Replace("-", "")
             }));
         }
         if (ProtectLoader.NetCrypt != null)
         {
             length = ProtectLoader.NetCrypt.Encrypt(ref buffer, length);
         }
         socket.SendTo(buffer, length, SocketFlags.None, ip);
         // UnityEngine.Debug.Log(length.ToString("X16"));
         return(result);
     }
     catch (Exception ex)
     {
         Debug.LogError(ex.Message);
         socket.Close();
     }
     return(0);
 }
Example #24
0
        private void Listen()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 61111);
            _socket.Bind(iep);
            _endPoint = (EndPoint)iep;

            while (true)
            {
                byte[] data = new byte[1024];
                try
                {
                    int recv = _socket.ReceiveFrom(data, ref _endPoint);
                    string s = Encoding.ASCII.GetString(data, 0, recv);
                    if (s == "Amleto client search")
                    {
                        string res = "Amleto server at " + _hostAddress + " " + Port;
                        byte[] bres = Encoding.ASCII.GetBytes(res);
                        _socket.SendTo(bres, _endPoint);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "Unable to start Listener");
                }
            }
        }
Example #25
0
        /// <summary>
        /// Send the data to the client.
        /// </summary>
        private void SendData()
        {
            // Get the data from the response stream.
            byte[] buffer = new byte[ReadBufferSize];

            // Send all in buffer until empty.
            while (_responseStream != null && _responseStream.Length > 0)
            {
                // Read the data.
                int byesRead = _responseStream.ReadFromStream(buffer, 0, buffer.Length);

                // Send to client if bytes have been read.
                if (byesRead > 0)
                {
                    // Lock the socket receive process.
                    lock (ServerRef.LockingSocket)
                    {
                        // Send the data back to the client.
                        _socket.SendTo(buffer, 0, byesRead, _sendSocketFlags, RemoteClient);
                    }

                    // If the time out control has been created
                    // then reset the timer.
                    InActiveTimeOutSetter();
                }
            }
        }
Example #26
0
 static void Send(byte[] data, string ip, int port)
 {
     Console.WriteLine(string.Format("Sending {0} bytes...", data.Length));
     Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
     sock.SendTo(data, endPoint);
 }
Example #27
0
        /// <summary>
        /// Send the magic packet on the broadcast IP address for wake on LAN functionality
        /// </summary>
        /// <param name="macAddress">MAC address destination for Wake on LAN</param>
        public static void Wake(byte[] macAddress)
        {
            // create UDP socket and set for broadcast
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);

            // set endpoint with broadcast ip address and WOL port
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(BROADCAST_IP_ADDRESS), WOL_PORT);

            // add magic packet header
            byte[] magicPacket = new byte[MAGIC_PACKET_SIZE];
            for (int i = 0; i < MAGIC_PACKET_HEADER_SIZE; i++)
                magicPacket[i] = 0xFF;

            // write 16 copies of mac address into magic packet
            int magicPacketIdx = MAGIC_PACKET_HEADER_SIZE;
            for (int i = 0; i < MAGIC_PACKET_MAC_ADDR_RIPETITION; i++)
            {
                for (int j = 0; j < MAC_ADDR_SIZE; j++)
                {
                    magicPacket[magicPacketIdx] = macAddress[j];
                    magicPacketIdx++;
                }
            }

            // send magic packet and close
            socket.SendTo(magicPacket, ipEndPoint);
            socket.Close();
        }
Example #28
0
        private void baseSend(object obj)
        {
            AbstractSocketData sockeData      = obj as AbstractSocketData;
            SocketMessager     socketMessager = new SocketMessager();

            socketMessager.encode(sockeData);
            byte[] dataBytes = socketMessager.DataBytes;
            if (dataBytes != null && dataBytes.Length > 0)
            {
                System.Net.Sockets.Socket socket = null;
                try
                {
                    System.Net.EndPoint remoteEP = new System.Net.IPEndPoint(this.ipAddress, this.port);
                    socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
                    socket.SendTo(dataBytes, dataBytes.Length, System.Net.Sockets.SocketFlags.None, remoteEP);
                    socket.Shutdown(System.Net.Sockets.SocketShutdown.Send);
                }
                catch (System.Exception)
                {
                }
                finally
                {
                    if (socket != null)
                    {
                        socket.Close();
                    }
                }
            }
        }
Example #29
0
        public bool Send(byte[] packet, int port)
        {
            Socket socket = null;

            try
            {
                socket = new Socket(
                            AddressFamily.InterNetwork,
                            SocketType.Dgram,
                            ProtocolType.Udp);

                socket.SetSocketOption(
                                SocketOptionLevel.Socket,
                                SocketOptionName.ReceiveTimeout,
                                2000);

                var hostEntry = Dns.Resolve(SnmpKeys.RECEIVER_IP);

                var endPoint = new IPEndPoint(hostEntry.AddressList[0], port);

                socket.SendTo(packet, packet.Length, SocketFlags.None, endPoint);

                return true;
            }
            catch (SocketException)
            {
                return false;
            }
            finally
            {
                if (socket != null)
                    socket.Dispose();
            }
        }
Example #30
0
        static void Main(string[] args)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            int port = 9999;

            IPEndPoint iep = new IPEndPoint(IPAddress.Loopback, port);
            byte[] rec = new byte[256];

            EndPoint ep = (EndPoint)iep;
            s.ReceiveTimeout = 1000;
            String msg;
            Boolean on = true;

            do
            {
                Console.Write(">");
                msg = Console.ReadLine();
                if (msg.Equals("Q"))
                {
                    on = false;
                }
                else
                {
                    s.SendTo(Encoding.ASCII.GetBytes(msg), ep);

                    while (!Console.KeyAvailable)
                    {
                        IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
                        EndPoint Palvelinep = (EndPoint)remote;
                        int paljon = 0;

                        try
                        {
                            paljon = s.ReceiveFrom(rec, ref Palvelinep);
                            // splitataan string, onko pituus 2
                            String rec_string = Encoding.ASCII.GetString(rec, 0, paljon);
                            char[] delim = { ';' };
                            String[] palat = rec_string.Split(delim, 2);

                            if (palat.Length < 2)
                            {
                                // lähetä virheviesti
                            }
                            else
                            {
                                Console.WriteLine("[{0}:{1}]", palat[0], palat[1]);
                            }

                        }
                        catch
                        {

                        }
                    }
                }

            } while (on);

            s.Close();
        }
        public static void SendWWTRemoteCommand(string targetIP, string command, string param)
        {
            Socket sockA = null;
            IPAddress target = null;
            sockA = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
            if(targetIP == "255.255.255.255")
            {
                sockA.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                target = IPAddress.Broadcast;

            }
            else
            {
                target = IPAddress.Parse(targetIP);
            }

            IPEndPoint bindEPA = new IPEndPoint(IPAddress.Parse(NetControl.GetThisHostIP()), 8099);
            sockA.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            sockA.Bind(bindEPA);

            EndPoint destinationEPA = (EndPoint)new IPEndPoint(target, 8089);

            string output = "WWTCONTROL2" + "," + Earth3d.MainWindow.Config.ClusterID + "," + command + "," + param;

            Byte[] header = Encoding.ASCII.GetBytes(output);

            sockA.SendTo(header, destinationEPA);
            sockA.Close();
        }
		/// <summary>
		/// Writes the IcmpPacket to the wire over the specified socket to the specified end point
		/// </summary>
		/// <param name="socket">The socket to write to</param>
		/// <param name="packet">The packet to write</param>
		/// <param name="ep">The end point to write to</param>
		/// <returns></returns>
		public virtual int Write(Socket socket, IcmpPacket packet, EndPoint ep)
		{
			/*
			 * check the parameters
			 * */

			if (socket == null)
				throw new ArgumentNullException("socket");

			if (socket == null)
				throw new ArgumentNullException("packet");

			if (socket == null)
				throw new ArgumentNullException("ep");

			// convert the packet to a byte array
			byte[] bytes = IcmpPacket.GetBytes(packet);

			// send the data using the specified socket, returning the number of bytes sent
			int bytesSent = socket.SendTo(bytes, bytes.Length, SocketFlags.None, ep);

			/*
			 * validate bytes sent
			 * */

			return bytesSent;
		}
Example #33
0
        public void Connect(EndPoint endPoint)
        {
            byte[] data = new byte[1024];
            string input, stringData;
            int recv;
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            int sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
            Console.WriteLine("Default timeout: {0}", sockopt);
            server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _timeout);
            sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
            Console.WriteLine("New timeout: {0}", sockopt);

            string welcome = "Hello, are you there?";
            data = Encoding.ASCII.GetBytes(welcome);
            server.SendTo(data, data.Length, SocketFlags.None, endPoint);

            data = new byte[1024];
            try
            {
                Console.WriteLine("Waiting from {0}:", endPoint.ToString());
                recv = server.ReceiveFrom(data, ref endPoint);
                Console.WriteLine("Message received from {0}:", endPoint.ToString());
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            }
            catch (SocketException e)
            {
                if (e.SocketErrorCode == SocketError.HostUnreachable)
                    throw new Exception("CLOSED");
                throw new Exception("TIME_OUT");
            }
            Console.WriteLine("Stopping client");
            server.Close();
        }
Example #34
0
        public override void start()
        {
            new Thread((ThreadStart)
                delegate()//不断发送广播
                {
                    Socket sockCon = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sockCon.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
#if UNITY_EDITOR
                    sockCon.Bind(new IPEndPoint(IPAddress.Parse(IPManager.getLanIP()), 13000));
#endif
                    IPEndPoint broad = new IPEndPoint(IPAddress.Broadcast, Const.PORT);

                    byte[] msg = new byte[4];

                    while (!isRunning)//当两个客户端(含自己)都连接成功后,isRunning将变为true,即广播结束
                    {
                        sockCon.SendTo(msg, broad);
                        Thread.Sleep(50);
                    }

                    sockCon.Close();
                    Console.WriteLine("stop sending broadcast");
                }
            ).Start();//开始广播自己

            base.start(IPManager.getLanIP());//启动tcp连接侦听
        }
Example #35
0
        public int SendUDP(byte[] bData, int nLength, System.Net.EndPoint ep)
        {
            lock (SyncRoot)
            {
                if (m_bReceive == false)
                {
                    this.LogError(MessageImportance.Highest, "error", string.Format("Can't call SendUDP, socket not valid or closed"));
                    return(0);
                }

                if (this.m_Logger != null)
                {
                    LogMessage(MessageImportance.Lowest, this.OurGuid, string.Format("SendUDP from {0} to {1}", s.LocalEndPoint, ep));
                }
                return(s.SendTo(bData, nLength, SendFlags, ep));
            }
        }
Example #36
0
        public void Send(byte[] sendByte, string dIP, int dPort)
        {
            sendPort = dPort;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(dIP), dPort);

            RemotePoint = (EndPoint)(ipep);
            mySocket.SendTo(sendByte, SocketFlags.None, RemotePoint);
        }
Example #37
0
        public void Send(int packageSize, string dIP, int dPort)
        {
            sendPort = dPort;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(dIP), dPort);

            RemotePoint = (EndPoint)(ipep);
            socket.SendTo(sendBuf_, packageSize, SocketFlags.None, RemotePoint);
        }
Example #38
0
 private void Run()
 {
     byte[] message = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString());
     for (int i = 0; i < 5; i++)
     {
         senderSocket.SendTo(message, endPoint);
         Console.WriteLine("Message Sent");
     }
 }
Example #39
0
        /// <summary>
        /// 初始化Kcp
        /// </summary>
        /// <param name="conv">会话</param>
        private void InitKcp(uint conv)
        {
            kcp = new KCP(conv, (buf, size) =>
            {
                server.SendTo(buf, 0, size, SocketFlags.None, remote);
            });

            kcp.NoDelay(1, 10, 2, 1);
            kcp.WndSize(128, 128);
        }
Example #40
0
        /// <summary>
        ///  向特定ip的主机的端口发送数据报
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void sendMsg(string msg, string ip, int port)
        {
            try
            {
                EndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);

                server.SendTo(Encoding.UTF8.GetBytes(msg), point);
            }
            catch (Exception ex)
            {
                OnError?.Invoke(this, new MsgArgs(ex.ToString()));
            }
        }
Example #41
0
        private void createAndSendUDP(String action)
        {
            System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            // send shooting command to nerf gun
            IPAddress serverAddr = IPAddress.Parse("192.168.1.142");

            IPEndPoint endPoint = new IPEndPoint(serverAddr, 4210);
            string     text     = action;

            byte[] send_buffer = Encoding.ASCII.GetBytes(text);
            sock.SendTo(send_buffer, endPoint);
            Console.Write("Sent to UDP value:" + action);
        }
Example #42
0
        /// <summary>
        /// Send the data to the client end point.
        /// </summary>
        /// <param name="data">The data to send.</param>
        /// <param name="client">The client end point to send to.</param>
        public void SendTo(byte[] data, IPEndPoint client)
        {
            if (data != null && data.Length > 0)
            {
                // Lock the socket receive process.
                lock (LockingSocket)
                {
                    // Get the client end point.
                    EndPoint endpoint = (EndPoint)client;

                    // Send the data back to the client.
                    _socket.SendTo(data, 0, data.Length, _sendSocketFlags, endpoint);
                }
            }
        }
Example #43
0
        public void SendTo(byte[] messageData, UdpEndPoint endPoint)
        {
            ThrowIfDisposed();

            if (messageData == null)
            {
                throw new ArgumentNullException("messageData");
            }
            if (endPoint == null)
            {
                throw new ArgumentNullException("endPoint");
            }

            _Socket.SendTo(messageData, new System.Net.IPEndPoint(IPAddress.Parse(endPoint.IPAddress), endPoint.Port));
        }
Example #44
0
        /// <summary>
        /// 发送UDP
        /// </summary>
        private bool sendUdp(string sIp, int iPort, byte[] sendByte)
        {
            bool bRet = false;

            try
            {
                System.Net.IPAddress  ip       = System.Net.IPAddress.Parse(sIp);
                System.Net.IPEndPoint serverIP = new System.Net.IPEndPoint(ip, iPort);

                System.Net.Sockets.Socket udpClient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
                udpClient.SendTo(sendByte, System.Net.Sockets.SocketFlags.None, serverIP);
                udpClient.Close();
                bRet = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送UDP出错:" + ex.Message);
            }
            return(bRet);
        }
Example #45
0
        /*************************************/

        private static bool SendAll(SS.Socket mySocket, IPEndPoint ePoint, byte[] data)
        {
            int totalbytes = data.Length;

            int bytessent = 0;             //Holds the total bytes sent

            while (bytessent < totalbytes) //While we still have more bytes to send
            {
                try
                {
                    int nbBytes   = Math.Min(5000, totalbytes - bytessent);
                    int RetnCheck = mySocket.SendTo(new ArraySegment <byte>(data, bytessent, nbBytes).ToArray(), ePoint); //Try to send remaining bytes
                    bytessent += RetnCheck;                                                                               //Add to total bytes sent
                    Thread.Sleep(50);
                }
                catch
                {
                    return(false);
                }
            }
            return(true); //Success!
        }
Example #46
0
        private byte[] QueryByUdp(DnsClientEndpointInfo endpointInfo, byte[] messageData, int messageLength, out IPAddress responderAddress)
        {
            using (System.Net.Sockets.Socket udpClient = new System.Net.Sockets.Socket(endpointInfo.LocalAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp))
            {
                try
                {
                    udpClient.ReceiveTimeout = QueryTimeout;

                    PrepareAndBindUdpSocket(endpointInfo, udpClient);

                    EndPoint serverEndpoint = new IPEndPoint(endpointInfo.ServerAddress, _port);

                    udpClient.SendTo(messageData, messageLength, SocketFlags.None, serverEndpoint);

                    if (endpointInfo.IsMulticast)
                    {
                        serverEndpoint = new IPEndPoint(udpClient.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, _port);
                    }

                    byte[] buffer = new byte[65535];
                    int    length = udpClient.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref serverEndpoint);

                    responderAddress = ((IPEndPoint)serverEndpoint).Address;

                    byte[] res = new byte[length];
                    Buffer.BlockCopy(buffer, 0, res, 0, length);
                    return(res);
                }
                catch (Exception e)
                {
                    Trace.TraceError("Error on dns query: " + e);
                    responderAddress = default(IPAddress);
                    return(null);
                }
            }
        }
Example #47
0
 int Utils.Wrappers.Interfaces.ISocket.SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, System.Net.EndPoint remoteEP)
 {
     return(InternalSocket.SendTo(buffer, offset, size, socketFlags, remoteEP));
 }
Example #48
0
    private static void Connect()
    {
        Task getPrimeNums = new Task(RSA.getPrimeNums);

        getPrimeNums.Start();

        while (localPort == -1 || remotePort == -1 || remoteIpAddress == "-1")
        {
            ;
        }

        try
        {
            listeningSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            Task listeningTask = new Task(Listen);
            listeningTask.Start();

            byte[]   data;
            EndPoint remotePoint = new IPEndPoint(IPAddress.Parse(remoteIpAddress), remotePort);

            if (!Handshake || !wasGettedKey || !wasGettedN || !wasGettedMainKey)
            {
                InfoMessage("Waiting for handshacke...");

                do
                {
                    Thread.Sleep(1000);
                    data = Encoding.Unicode.GetBytes("0");
                    listeningSocket.SendTo(data, remotePoint);
                    Thread.Sleep(10);
                }       while (!Handshake);

                MyKeys = RSA.getKeys();

                InfoMessage("Sending keys...");

                do
                {
                    data = Encoding.Unicode.GetBytes(Convert.ToString(MyKeys[0]));                     //Отправляем N
                    listeningSocket.SendTo(data, remotePoint);
                    Thread.Sleep(1000);
                } while (!wasGettedN);

                do
                {
                    data = Encoding.Unicode.GetBytes(Convert.ToString(MyKeys[1]));                     //Отправляем e
                    listeningSocket.SendTo(data, remotePoint);
                    Thread.Sleep(1000);
                } while (!wasGettedKey);

                InfoMessage("Connecting...");

                do
                {
                    data = Encoding.Unicode.GetBytes(Convert.ToString(PrimeTest.quickMod(
                                                                          MyMainKey, HerOpenKey[1], HerOpenKey[0])));
                    listeningSocket.SendTo(data, remotePoint);
                    Thread.Sleep(1000);
                } while(!wasGettedMainKey);

                Thread.Sleep(3000);
            }
        }
        catch (Exception ex)
        {
            InfoMessage(Convert.ToString(ex));
        }

        InfoMessage("Connected!");
    }
Example #49
0
    //*********************************************************************
    /// <summary>
    /// Send bytes over the socket
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    //*********************************************************************

    public async Task <bool> Send(System.Byte[] message)
    {
        var bytesSent = sock.SendTo(message, endpoint);

        return(true);
    }
        /// <summary>
        /// 向远端主机的端口发送数据报
        /// </summary>
        public FunctionResult UdpConnectLocalSendMessage(byte[] message, uint messageLength)
        {
            UdpConnectRemoteSocket.SendTo(message, UdpConnectRemoteEndPoint);

            return(FunctionResult.Success);
        }