private static void Server() { list = new List<IPAddress>(); const ushort data_size = 0x400; // = 1024 byte[] data; while (ServerRun) { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, BroadcastRecievePort); try { sock.Bind(iep); EndPoint ep = (EndPoint)iep; data = new byte[data_size]; if (!ServerRun) break; int recv = sock.ReceiveFrom(data, ref ep); string stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv); if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0]))) list.Add(IPAddress.Parse(ep.ToString().Split(':')[0])); data = new byte[data_size]; if (!ServerRun) break; recv = sock.ReceiveFrom(data, ref ep); stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv); if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0]))) list.Add(IPAddress.Parse(ep.ToString().Split(':')[0])); sock.Close(); } catch { } } }
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(); }
//static string broadCast = string.Empty; public static void StartBroadcastServer() { for (; Program.isProgramAlive ; ) { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, BroadcastRecievePort); sock.Bind(iep); EndPoint ep = (EndPoint)iep; Console.WriteLine("Ready to receive..."); byte[] data = new byte[1024]; int recv = sock.ReceiveFrom(data, ref ep); string stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString()); sendBroadcastAnswer(); data = new byte[1024]; recv = sock.ReceiveFrom(data, ref ep); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString()); sendBroadcastAnswer(); sock.Close(); } }
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(); }
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(); }
public void Listen() { int port = 9050; if (Options.listenMode != 0) { port = Options.listenMode; } int recv; byte[] data = new byte[4096]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); Console.WriteLine("Listening on UDP port " + port + " for squid log messages."); //Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)(sender); recv = newsock.ReceiveFrom(data, ref Remote); if (Options.debug == true) { Console.WriteLine("Message received from {0}:", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); } var initSeparatedMessages = Encoding.ASCII.GetString(data, 0, recv).Split((new char[] { '\n', '\r' }), StringSplitOptions.RemoveEmptyEntries); HelperMethods.addLog(initSeparatedMessages); while (true) { data = new byte[4096]; recv = newsock.ReceiveFrom(data, ref Remote); if (Options.debug == true) { Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); } var separatedMessages = Encoding.ASCII.GetString(data, 0, recv).Split((new char[] {'\n', '\r'}), StringSplitOptions.RemoveEmptyEntries); HelperMethods.addLog(separatedMessages); newsock.SendTo(data, recv, SocketFlags.None, Remote); } }
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); }
private void StartListening(Socket server) { EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int recv = 0; byte[] data = new byte[1024]; while (_running) { recv = 0; data = new byte[1024]; recv = server.ReceiveFrom(data, ref remoteEP); ICommand command = SerializeHelper.BytesToObject(data) as ICommand; if (command != null) { switch (command.CommandName) { case CommandFlags.Subscribe: Filter.AddSubscriber(command.TopicName, remoteEP); break; case CommandFlags.UnSubscribe: Filter.RemoveSubscriber(command.TopicName, remoteEP); break; default: break; } } } }
/// <summary> /// Reads an IcmpPacket from the wire using the specified socket from the specified end point /// </summary> /// <param name="socket">The socket to read</param> /// <param name="packet">The packet read</param> /// <param name="ep">The end point read from</param> /// <returns></returns> public virtual bool Read(Socket socket, EndPoint ep, int timeout, out IcmpPacket packet, out int bytesReceived) { const int MAX_PATH = 256; packet = null; bytesReceived = 0; /* * check the parameters * */ if (socket == null) throw new ArgumentNullException("socket"); if (socket == null) throw new ArgumentNullException("ep"); // see if any data is readable on the socket bool success = socket.Poll(timeout * 1000, SelectMode.SelectRead); // if there is data waiting to be read if (success) { // prepare to receive data byte[] bytes = new byte[MAX_PATH]; bytesReceived = socket.ReceiveFrom(bytes, bytes.Length, SocketFlags.None, ref ep); /* * convert the bytes to an icmp packet * */ // packet = IcmpPacket.FromBytes(bytes); } return success; }
public static string getUdpLine(Socket sock, EndPoint ep) { byte[] data = new byte[1024]; int recv = sock.ReceiveFrom(data, ref ep); string stringData = Encoding.ASCII.GetString(data, 0, recv); return stringData; }
private void computerFinderListener_DoWork(object sender, DoWorkEventArgs e) { Socket sockl = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint ipepl = new IPEndPoint(IPAddress.Any, 7829); sockl.Bind(ipepl); EndPoint ep = ipepl as EndPoint; Byte[] recv = new Byte[1024]; sockl.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000); while (!computerFinderListener.CancellationPending) { try { recv = new Byte[1024]; sockl.ReceiveFrom(recv, ref ep); String[] recvl = Encoding.UTF8.GetString(recv).Substring(4).TrimEnd('\0').Split(','); computerFinderListener.ReportProgress(-1, new CompFound() { hostname = recvl[0], ip = recvl[1] }); } catch (Exception) { //do nothing, timeout is only thing that can throw an exception anyway } } sockl.Close(); }
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(); }
private void listenBroadcast() { Console.WriteLine("listen broadcast..."); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, Setting.Port); socket.Bind(endPoint); byte[] buffer = new byte[VERIFY_KEY_BUFFER_SIZE]; while (true) { int res = 0; try { res = socket.ReceiveFrom(buffer, ref mRemote); String msg = Encoding.Default.GetString(buffer, 0, res); Log.v("msg:" + msg); BroadcastMsg broadcastMsg = new BroadcastMsg(msg); if (Verify.verifyBroadcastMsg(broadcastMsg)) { addToPadList(broadcastMsg, ((IPEndPoint)mRemote).Address); } } catch (Exception e) { Console.WriteLine("illegal client request! from " + mRemote.ToString()); } } }
static void Start() { var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //var ip = new IPAddress(new byte[] { 192, 168, 1, 87 }); var endPoint = new IPEndPoint(IPAddress.Any, MAPLE_SERVER_BROADCASTPORT); socket.Connect(endPoint); //byte[] bytesToSend = Encoding.UTF8.GetBytes(msg); while (true) { //socket.SendTo(bytesToSend, bytesToSend.Length, SocketFlags.None, endPoint); while (socket.Poll(2000000, SelectMode.SelectRead)) { if (socket.Available > 0) { byte[] inBuf = new byte[socket.Available]; EndPoint recEndPoint = new IPEndPoint(IPAddress.Any, 0); socket.ReceiveFrom(inBuf, ref recEndPoint); //if (!recEndPoint.Equals(endPoint))// Check if the received packet is from the 192.168.0.2 // continue; Debug.WriteLine(new String(Encoding.UTF8.GetChars(inBuf))); } } Thread.Sleep(100); } }
public static void Start() { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); listener.Bind(new IPEndPoint(IPAddress.Any, PORT)); Console.WriteLine("Waiting for a connection..." + GetLocalIpAddress()); while (true) { EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); StateObject state = new StateObject(); state.WorkSocket = listener; listener.ReceiveFrom(state.Buffer, ref remoteEndPoint); var rawMessage = Encoding.UTF8.GetString(state.Buffer); var messages = rawMessage.Split(';'); if (messages.Length > 1) { var command = messages[0]; var deviceName = messages[1]; Console.WriteLine("Command is received from Device Name +"+deviceName+"+"); string[] portno = remoteEndPoint.ToString().Split(':'); Send(portno[1],remoteEndPoint); } } }
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; }
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"); } } }
/// <summary> /// /// </summary> /// <param name="server"></param> private void StartListening(Socket server) { EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int recv = 0; byte[] data = new byte[1024]; while (_shouldStop == false) { try { recv = 0; data = new byte[1024]; recv = server.ReceiveFrom(data, ref remoteEP); ICommand command = SerializeHelper.BytesToObject(data) as ICommand; if (command != null) { if (command.CommandName == CommandFlags.Publish) { if (!string.IsNullOrEmpty(command.TopicName)) { List<EndPoint> subscriberListForThisTopic = Filter.GetSubscribers(command.TopicName); WorkerThreadParameters workerThreadParameters = new WorkerThreadParameters(); workerThreadParameters.Server = server; workerThreadParameters.Message = command.Data; workerThreadParameters.SubscriberListForThisTopic = subscriberListForThisTopic; ThreadPool.QueueUserWorkItem(new WaitCallback(Publish), workerThreadParameters); } } } } catch { } } }
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(); }
public void Start(int port) { Console.WriteLine("UPD Server on " + port + " ..."); var sep = new IPEndPoint(IPAddress.Any, port); _udp_socket = new Socket(sep.AddressFamily, SocketType.Dgram, ProtocolType.Udp); _udp_socket.Bind(sep); while (true) { var s = new byte[1024]; EndPoint ep = new IPEndPoint(IPAddress.Any, 0); try { var read = _udp_socket.ReceiveFrom(s, ref ep); if (read > 0) { Console.WriteLine("UDP recv ok from " + ep); } } catch (SocketException e) { Console.WriteLine(e.Message); } } }
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(); }
static void Main(string[] args) { int recv; byte[] data = new byte[1024]; Socket newsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); serverin("files/serverin.txt"); //LISTEN TO ANY ip on port 950 IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, PORT); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)(sender); //BIND ANY CONNECTION ON ENDPOINT TO NEWSOCKET newsocket.Bind(endpoint); Console.WriteLine("waiting for a client ..."); //WAIT FOR CLIENT TO Request data recv = newsocket.ReceiveFrom(data, ref Remote); //store end point in Remote string filename = Encoding.ASCII.GetString(data); filename = filename.Replace("\0", string.Empty); Console.WriteLine("Received request for file: " + filename); startChild(filename, Remote, newsocket); Console.WriteLine("Sending Complete"); Console.ReadLine(); }
static void Main(string[] args) { Templates _templates = new Templates(); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9991); sock.Bind(iep); EndPoint ep = (EndPoint)iep; byte[] data = new byte[2048]; while (true) { int recv = sock.ReceiveFrom(data, ref ep); //Console.ReadKey(); Console.Clear(); byte[] bytes = new byte[recv]; for (int i = 0; i < recv; i++) bytes[i] = data[i]; Packet packet = new Packet(bytes, _templates); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(packet.ToString()); } sock.Close(); Console.ReadKey(); }
/// <summary> /// Try to update both system and RTC time using the NTP protocol /// </summary> /// <param name="TimeServer">Time server to use, ex: pool.ntp.org</param> /// <param name="GmtOffset">GMT offset in minutes, ex: -240</param> /// <returns>Returns true if successful</returns> public DateTime NTPTime(string TimeServer, int GmtOffset = 0) { Socket s = null; DateTime resultTime = DateTime.Now; try { EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123); s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); byte[] ntpData = new byte[48]; Array.Clear(ntpData, 0, 48); ntpData[0] = 0x1B; // Set protocol version s.SendTo(ntpData, rep); // Send Request if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout { s.ReceiveFrom(ntpData, ref rep); // Receive Time byte offsetTransmitTime = 40; ulong intpart = 0; ulong fractpart = 0; for (int i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i]; for (int i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i]; ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L); s.Close(); resultTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond); Utility.SetLocalTime(resultTime.AddMinutes(GmtOffset)); } s.Close(); } catch { try { s.Close(); } catch { } } return resultTime; }
public void GetSocketResponse(Socket socket) { try { while (true) { var response = new byte[8000]; EndPoint ep = new IPEndPoint(IPAddress.Any, multicastPort); socket.ReceiveFrom(response, ref ep); try { var receivedString = Encoding.UTF8.GetString(response); var location = receivedString.Substring(receivedString.ToLower().IndexOf("location:", System.StringComparison.Ordinal) + 9); receivedString = location.Substring(0, location.IndexOf("\r", System.StringComparison.Ordinal)).Trim(); _discoveredDevices.Add(receivedString); } catch { //Not a UTF8 string, ignore this response. } } } catch { //TODO handle exception for when connection closes } }
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) }; } }
void UdpEchoClientTimeoutSocketMethod(string[] args) { //Check for correct amount of arguments if ((args.Length < 2) || (args.Length > 3)) throw new ArgumentException("Parameters: <Server> <Word> [<Port>]"); //Name/IPAddress string server = args[0]; //Use port argument if supplied, otherwise default to 7 int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7; //Create a socket that is connected to the server on a specified port Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //Set the receive timeout for this scket sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, TIMEOUT); IPEndPoint remoteIPEndPoint = new IPEndPoint(Dns.GetHostAddresses(server)[0], servPort); EndPoint remoteEndPoint = (EndPoint)remoteIPEndPoint; //Convert input string to an array of bytes. byte[] sendPacket = Encoding.ASCII.GetBytes(args[1]); byte[] rcvPacket = new byte[sendPacket.Length]; //Packets may be lost, so we have to keep trying int tries = 0; bool rcvdResponse = false; do { //Send the echo string sock.SendTo(sendPacket, remoteEndPoint); Console.WriteLine("Sent {0} bytes to the server...", sendPacket.Length); try { //Attempt echo reply service sock.ReceiveFrom(rcvPacket, ref remoteEndPoint); rcvdResponse = true; } catch (SocketException se) { tries++; //WSAETIMEDOUT: Connection timed out if (se.ErrorCode == 10060) Console.WriteLine("Timed out, {0} more tries...", (MAXTRIES - tries)); else Console.WriteLine(se.ErrorCode + ": " + se.Message); } } while ((!rcvdResponse) && (tries < MAXTRIES)); if (rcvdResponse) Console.WriteLine("Received {0} bytes from {1}: \"{2}\"", rcvPacket.Length, remoteEndPoint, Encoding.ASCII.GetString(rcvPacket, 0, rcvPacket.Length)); else Console.WriteLine("No response...\r\n\t- Please check your connection and try again."); sock.Close(); }
public void portlisten() { System.Net.Sockets.Socket udplistener= new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint local = new IPEndPoint(myip,9090); udplistener.Bind(local); listening=new Thread(new ThreadStart( delegate() { while (true) { IPEndPoint i = new IPEndPoint(IPAddress.Any,9090); EndPoint client = (EndPoint)i; byte[] buffer = new byte[1024]; int rev = udplistener.ReceiveFrom(buffer, ref client); string 客户端 = System.Text.Encoding.UTF8.GetString(buffer); SpaceName your = isay(客户端); SpaceName my = new SpaceName(); if (myspacenamelist.ContainsKey(your.NameHead)) my = myspacenamelist[your.NameHead]; SpaceName ret = new SpaceName(); ret.NameHead = your.NameHead; if (Mirror.Atom.Equal+Mirror.Unicode8.toMirror(client.ToString()) == my["(1983&1&1,###,###)"]) { ret.Add("(1983&1&1,###,###)", my["(1983&1&1,###,###)"]); udplistener.SendTo(System.Text.Encoding.UTF8.GetBytes(ret.ToString()), client); } else { foreach (KeyValuePair<string, string> m in my) { foreach (KeyValuePair<string, string> n in your) { if (n.Value == m.Value) { ret.Add("(1983&1&1,###,###)",Mirror.Atom.Equal+Mirror.Unicode8.toMirror( client.ToString())); goto END; } } } udplistener.SendTo(System.Text.Encoding.UTF8.GetBytes(ret.ToString()), client); continue; END: { my["(1983&1&1,###,###)"] = Mirror.Atom.Equal + Mirror.Unicode8.toMirror(client.ToString()); udplistener.SendTo(System.Text.Encoding.UTF8.GetBytes(ret.ToString()), client); } } } } )); listening.Start(); }
public void Run() { int len; byte[] packet = new byte[buff_size]; EndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); while (mcast_receiver != null && mcast_recv_sock != null) { try { len = mcast_recv_sock.ReceiveFrom(packet, ref remoteIpEndPoint); if (len == 1 && packet[0] == 0) { if (enclosingInstance.Stack.NCacheLog.IsInfoEnabled) { enclosingInstance.Stack.NCacheLog.Info("UDP.Run()", "received dummy packet"); } continue; } if (len > packet.Length) { enclosingInstance.Stack.NCacheLog.Error("UDP.Run()", "size of the received packet (" + len + ") is bigger than " + "allocated buffer (" + packet.Length + "): will not be able to handle packet. " + "Use the FRAG protocol and make its frag_size lower than " + packet.Length); } if (Version.CompareTo(packet) == false) { if (discard_incompatible_packets) { continue; } } handleIncomingPacket(packet, len); } catch (SocketException sock_ex) { enclosingInstance.Stack.NCacheLog.Error("MPingReceiver.Run()", "multicast socket is closed, exception=" + sock_ex); break; } catch (IOException ex) { enclosingInstance.Stack.NCacheLog.Error("MPingReceiver.Run()", "exception=" + ex); // thread was interrupted ; // go back to top of loop, where we will terminate loop } catch (System.Exception ex) { enclosingInstance.Stack.NCacheLog.Error("MPingReceiver.Run()", "exception=" + ex + ", stack trace=" + ex.StackTrace); Util.Util.sleep(200); // so we don't get into 100% cpu spinning (should NEVER happen !) } } }
static void Main(string[] args) { Socket s = null; int port = 9999; IPEndPoint iep = new IPEndPoint(IPAddress.Loopback, port); List<EndPoint> asiakkaat = new List<EndPoint>(); try { s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); s.Bind(iep); } catch (Exception ex) { Console.WriteLine("Virhe... " + ex.Message); Console.ReadKey(); return; } Console.WriteLine("Odotetaan asiakasta"); while (!Console.KeyAvailable) { byte[] rec = new byte[256]; IPEndPoint asiakas = new IPEndPoint(IPAddress.Any, 0); EndPoint remote = (EndPoint)asiakas; int received = s.ReceiveFrom(rec, ref remote); String rec_string = Encoding.ASCII.GetString(rec, 0, received); char[] delim = { ';' }; String[] palat = rec_string.Split(delim, 2); if (palat.Length < 2) { // lähetävirheviesti } else { if (!asiakkaat.Contains(remote)) { asiakkaat.Add(remote); Console.WriteLine("Uusi asiakas: [{0}:{1}]", ((IPEndPoint)remote).Address, ((IPEndPoint)remote).Port); } Console.WriteLine("[{0}:{1}]", palat[0], palat[1]); foreach (EndPoint client in asiakkaat) { //String kaikille = palat[0] + ": " + palat[1]; // lähetä rec_string s.SendTo(Encoding.ASCII.GetBytes(rec_string), client); } } } }
public void run() { try { IPEndPoint ip = new IPEndPoint(IPAddress.Any, listenPort); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(ip); Logger.getInstance().log("Listening on port " + listenPort, LOGGING_NAME, Logger.Level.INFO); while (true) { IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint senderEP = (EndPoint)(sender); Byte[] buffer = new Byte[DATAGRAM_SIZE]; socket.ReceiveFrom(buffer, ref senderEP); MemoryStream ms = new MemoryStream(buffer); DataInputStream dis = new DataInputStream(ms); int size = dis.readInt(); int type = dis.readInt(); byte[] data = new byte[size]; System.Array.Copy(buffer, 2*sizeof(Int32) /*8*/, data, 0, size); Message m = Message.Unserialize(Message.fromInt(type), data, (IPEndPoint)senderEP); storage.put(m); } } catch (SocketException) { Logger.getInstance().log("Could not listen on port " + listenPort, LOGGING_NAME, Logger.Level.SEVERE); } catch (IOException) { Logger.getInstance().log("Error reading packet!", LOGGING_NAME, Logger.Level.INFO); } catch (InvalidMessageTypeException e) { Logger.getInstance().log("InvalidMessageTypeException " + e.Message, LOGGING_NAME, Logger.Level.WARNING); } catch (ThreadInterruptedException e) { Logger.getInstance().log("InterruptedException " + e.Message, LOGGING_NAME, Logger.Level.WARNING); } Thread.CurrentThread.Abort(); }
public void KcpListen() { while (!exitFlag) { var data = new byte[1024]; var recv = server.ReceiveFrom(data, ref remote); var callbackBuff = new byte[recv]; Buffer.BlockCopy(data, 0, callbackBuff, 0, recv); receiveQueue.Push(callbackBuff); } }
private void ServiceDiscovery_Load(object sender, EventArgs e) { //Thread t = new Thread(listen); //t.Start(); Boolean exception_thrown = false; Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sending_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); IPAddress send_to_address = IPAddress.Parse("255.255.255.255"); IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 1900); string text_to_send = "TYPE: WM-DISCOVER\r\nVERSION: 1.0\r\n\r\nservices: com.rtcoa.tstat*\r\n\r\n"; byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send); EndPoint ep = (EndPoint)sending_end_point; byte[] buff = new byte[1024]; try { //Thread t = new Thread(timeout); //t.Start(); sending_socket.SendTo(send_buffer, sending_end_point); //EndPoint ep = sending_end_point.Create(sending_socket.a); // while (true) //{ sending_socket.ReceiveFrom(buff, ref ep); String str = Encoding.ASCII.GetString(buff); richTextBox1.Text = str; //} } catch (Exception send_exception) { exception_thrown = true; richTextBox1.Text = " Exception " + send_exception.Message; } if (exception_thrown == false) { richTextBox1.Text = richTextBox1.Text + "Message has been sent to the broadcast address"; } else { exception_thrown = false; richTextBox1.Text = "The exception indicates the message was not sent."; } }
public static void StartListening() { // Data buffer for incoming data. byte[] bytes = new Byte[1024]; try { //listener.Listen(10); while (true) { // Establish the local endpoint for the socket. IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Program.PORT); // Create a UDP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // Set the event to nonsignaled state. listener.Bind(localEndPoint); allDone.Reset(); // Start an asynchronous socket to listen for connections. Console.WriteLine("Waiting for a UDP connection..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 9046); EndPoint tmpRemote = (EndPoint)sender; int recv = listener.ReceiveFrom(bytes, ref tmpRemote); Console.Write("Message recv from: {0}", tmpRemote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, recv)); listener.Connect(tmpRemote); listener.Send(bytes); listener.Close(); // Create the state object. //StateObject state = new StateObject(); //state.workSocket = listener; //state.ep = tmpRemote; //state.workSocket.BeginReceiveFrom(state.buffer, 0, StateObject.BufferSize, 0, ref tmpRemote, new AsyncCallback(ReceiveCallback), state);//(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); // Wait until a connection is made before continuing. allDone.WaitOne(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); }
public void ReceiveHandle() { while (runningFlag) { try { int length = socket.ReceiveFrom(recv, ref RemotePoint); if (length > 0) { ReceiveData(recv); Array.Clear(recv, 0, 1024); } } catch (Exception e) { } } }
private void ReceiveHandle() { while (runningFlag) { try { length = mySocket.ReceiveFrom(recv, ref RemotePoint); if (length > 0 && recv[2] == 3) { processData(recv); } recv = new byte[1024]; } catch (Exception e) { } } }
/// <summary> /// 接收到的数据 /// </summary> public void ReciveMsg() { try { while (true) { EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号 byte[] buffer = new byte[1024]; int length = server.ReceiveFrom(buffer, ref point);//接收数据报 string message = Encoding.UTF8.GetString(buffer, 0, length); // Console.WriteLine(point.ToString() + message); OnReciveMsg?.Invoke(this, new MsgArgs(point.ToString() + "," + message)); } } catch (Exception ex) { OnError?.Invoke(this, new MsgArgs(ex.ToString())); } }
public static int uLink_DoNetworkRecv(System.Net.Sockets.Socket socket, ref byte[] buffer, ref EndPoint ip) { try { int length = socket.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ip); if (ProtectLoader.NetCrypt != null) { length = ProtectLoader.NetCrypt.Decrypt(ref buffer, length); } if (ProtectLoader.Netlog && (length > 0)) { Debug.Log(string.Concat(new object[] { "Network.Recv(", ip, ").Packet(", length, "): ", BitConverter.ToString(buffer, 0, length).Replace("-", "") })); } return(length); } catch (Exception exception) { Debug.LogError(exception.Message); socket.Close(); } return(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); } } }
int Utils.Wrappers.Interfaces.ISocket.ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { return(InternalSocket.ReceiveFrom(buffer, offset, size, socketFlags, ref remoteEP)); }
public static int uLink_DoNetworkRecv(System.Net.Sockets.Socket socket, ref byte[] buffer, ref EndPoint ip) { int result; try { int num = socket.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ip); int num3; if (!Hooks.NetworkBlacklistIP.Contains(ip) && num >= 8) { int hashCode = ip.GetHashCode(); ulong num2 = BitConverter.ToUInt64(buffer, 0); if (num2 != 8242523046020120583uL) { if (!Hooks.NetworkPacketLast.ContainsKey(hashCode)) { Hooks.NetworkPacketLast.Add(hashCode, new Hooks.NetworkPacketStamp()); } Hooks.NetworkPacketLast[hashCode].Flood++; if (Hooks.NetworkPacketLast[hashCode].Flood > 255 && !Hooks.NetworkBlacklistIP.Contains(ip)) { result = 0; return(result); } if (Time.time < Hooks.NetworkPacketLast[hashCode].Time) { Hooks.NetworkPacketLast[hashCode].Count++; } else { Hooks.NetworkPacketLast[hashCode].Count = 0; Hooks.NetworkPacketLast[hashCode].Time = Time.time + 1f; } if ((float)Hooks.NetworkPacketLast[hashCode].Count > NetCull.sendRate * 10f) { num3 = 0; result = num3; return(result); } if (Hooks.NetworkPacketLast[hashCode].ID == num2 && Hooks.NetworkPacketLast[hashCode].Size == num) { num3 = 0; result = num3; return(result); } Hooks.NetworkPacketLast[hashCode].ID = num2; Hooks.NetworkPacketLast[hashCode].Size = num; Hooks.NetworkPacketLast[hashCode].Flood = 0; } object[] array = new object[] { socket, buffer, num, ip }; int asInt = Method.Invoke("RustExtended.RustHook.uLink_DoNetworkRecv", array).AsInt; buffer = (byte[])array[1]; ip = (EndPoint)array[3]; num3 = asInt; result = num3; return(result); } num3 = 0; result = num3; return(result); } catch (Exception ex) { UnityEngine.Debug.LogError(ex.ToString()); } result = 0; return(result); }
/// <summary> /// 接收发送给本机ip对应端口号的数据报 /// </summary> public FunctionResult UdpConnectLocalReceiveMessage(ref byte[] message, ref uint messageLength) { messageLength = (uint)UdpConnectRemoteSocket.ReceiveFrom(message, ref UdpConnectRemoteEndPoint); return(FunctionResult.Success); }