/// <summary> /// 向客户端异步发送文件 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="filePath"></param> public async Task SendToClientFileAsync(string ip, int port, string filePath, Message msg) { // 新建 Udp 用于发送文件 var sendClient = new UdpClient(); try { FileInfo fileInfo = new FileInfo(filePath); msg.Type = MessageEnum.FILE; // 设置发送文件标识 msg.FileLength = fileInfo.Length; msg.FileName = Regex.Match(filePath, @"\\([^\\]+\.[^\\]+)").Groups[1].Value; // 获取文件名 byte[] datagram = Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(msg)); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port); /* * 向‘原’远程客户端发送请求传送文件的请求, * 接收‘新’远程客户端的响应,获取传送文件的端口 * * 注:原远程客户端用于发送消息,新远程客户端用于发送文件 */ await sendClient.SendAsync(datagram, datagram.Length, endPoint); //IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); UdpReceiveResult result = await sendClient.ReceiveAsync().ConfigureAwait(false); // 阻塞直到接收到远程客户端的响应 /* * 开始发送文件 */ byte[] buffer = new byte[MAXSIZE]; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1, true)) { int percent = 0; int count = 0; while ((count = await fs.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) { //await Task.Delay(10); await sendClient.SendAsync(buffer, count, result.RemoteEndPoint); if (Client.SendFileProgressNotify != null) { Client.SendFileProgressNotify(String.Format("{0:F2}%", (percent += count) / msg.FileLength * 100)); } } sendClient.Close(); } } catch (Exception e) { Log.Write(e.Message); } }
protected virtual void ReceiveConnect(ConnectMessage connectMessage) { UdpTrackerMessage m = new ConnectResponseMessage(connectMessage.TransactionId, CreateConnectionID()); byte[] data = m.Encode(); #if NETSTANDARD1_5 listener.SendAsync(data, data.Length, endpoint); #else listener.Send(data, data.Length, endpoint); #endif }
private async Task SendText() { try { var buffer = Encoding.ASCII.GetBytes(TbSendContext.Text); await _client.SendAsync(buffer, buffer.Length); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task SendToServer(byte[] message) { lastActivity = DateTime.UtcNow; await _tcs.Task; var sent = await client.SendAsync(message, message.Length, _remoteServer); }
private async Task SendWakeOnLan(string macAddress, IPEndPoint endPoint, CancellationToken cancellationToken) { const int payloadSize = 102; var macBytes = PhysicalAddress.Parse(macAddress).GetAddressBytes(); _logger.Debug(String.Format("Sending magic packet to {0}", macAddress)); // Construct magic packet var payload = new byte[payloadSize]; Buffer.BlockCopy(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, 0, payload, 0, 6); for (var i = 1; i < 17; i++) { Buffer.BlockCopy(macBytes, 0, payload, 6 * i, 6); } // Send packet LAN using (var udp = new UdpClient()) { udp.Connect(endPoint); cancellationToken.ThrowIfCancellationRequested(); await udp.SendAsync(payload, payloadSize).ConfigureAwait(false); } }
private void Run() { Task.Run(async() => { client.Client.Bind(new IPEndPoint(IPAddress.Any, 0)); _tcs.SetResult(true); using (client) { while (_isRunning) { try { var result = await client.ReceiveAsync(); lastActivity = DateTime.UtcNow; var sent = await _server.SendAsync(result.Buffer, result.Buffer.Length, _clientEndpoint); Console.WriteLine($"{sent} bytes sent from a return message of {result.Buffer.Length} bytes from {_remoteServer} to {_clientEndpoint}"); } catch (Exception ex) { Console.WriteLine($"An exception occurred while recieving a server datagram : {ex}"); } } } }); }
public async Task SendToServer(byte[] message) { lastActivity = DateTime.UtcNow; await _tcs.Task; var sent = await client.SendAsync(message, message.Length, _remoteServer); Console.WriteLine($"{sent} bytes sent from a client message of {message.Length} bytes from {_clientEndpoint} to {_remoteServer}"); }
private async void FindServers(Action<ServerDiscoveryInfo> serverFound, Action<Exception> error, CancellationToken cancellationToken) { var serverIdsFound = new List<string>(); // Create a udp client using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort()))) { // Construct the message the server is expecting var bytes = Encoding.UTF8.GetBytes("who is EmbyServer?"); // Send it - must be IPAddress.Broadcast, 7359 var targetEndPoint = new IPEndPoint(IPAddress.Broadcast, 7359); try { // Send the broadcast await client.SendAsync(bytes, bytes.Length, targetEndPoint).ConfigureAwait(false); while (!cancellationToken.IsCancellationRequested) { // Get a result back var result = await client.ReceiveAsync().ConfigureAwait(false); if (result.RemoteEndPoint.Port == targetEndPoint.Port) { // Convert bytes to text var json = Encoding.UTF8.GetString(result.Buffer); _logger.Debug("Received response from endpoint: " + result.RemoteEndPoint + ". Response: " + json); if (!string.IsNullOrEmpty(json)) { try { var info = _jsonSerializer.DeserializeFromString<ServerDiscoveryInfo>(json); if (!serverIdsFound.Contains(info.Id)) { serverIdsFound.Add(info.Id); info.EndpointAddress = result.RemoteEndPoint.Address.ToString(); serverFound(info); } } catch (Exception ex) { _logger.ErrorException("Error parsing server discovery info", ex); } } } } } catch (Exception ex) { error(ex); } } }
protected async Task replyUdpAsync(String replyMessage, IPAddress ip, int port) { UdpClient udpClient = new UdpClient(); udpClient.MulticastLoopback = true; udpClient.ExclusiveAddressUse = false; byte[] bytes = Encoding.ASCII.GetBytes(replyMessage); await udpClient.SendAsync(bytes, bytes.Length, new IPEndPoint(ip, port)); udpClient.Close(); }
public async Task<List<IPEndPoint>> GetParsedServers(CancellationToken cancelToken, int limit = -1, IPEndPoint remote = null, int tried = -1) { var cur = -1; var servers = new List<IPEndPoint>(); if (remote == null) { var hosts = await Dns.GetHostAddressesAsync("hl2master.steampowered.com").ConfigureAwait(false); if (tried == -1) cur = new Random().Next(hosts.Length); else cur = (tried + 1)%hosts.Length; var host = hosts[cur]; const int port = 27011; remote = new IPEndPoint(host, port); //TODO: alternate ip and ports availability } var e = new IPEndPoint(IPAddress.Any, 0); var udpClient = new UdpClient(e) { Client = {ReceiveTimeout = Consts.DefaultReceiveTimeout, SendTimeout = Consts.DefaultSendTimeout } }; var i = 0; const int maxIterations = 30; string lastSeed; var seed = "0.0.0.0:0"; do { cancelToken.ThrowIfCancellationRequested(); lastSeed = seed; var msg = BuildMessage(seed); if (await udpClient.SendAsync(msg, msg.Length, remote).ConfigureAwait(false) != msg.Length) throw new Exception("Send failed."); byte[] response = null; var timedOut = false; try { response = (await udpClient.ReceiveWithTimeoutAfter(Consts.DefaultReceiveTimeout, cancelToken).ConfigureAwait(false)) .Buffer; } catch (TimeoutException) { timedOut = true; if ((cur == -1) || (tried != -1) || (i != 0)) { throw new TimeoutException(string.Format("Received timeout on try: {0} packet: {1}", tried == -1 ? 1 : 2, i)); } } //only retries when remote was not passed in, on the first try, and when the first packet was never received if (timedOut) return await GetParsedServers(cancelToken, limit, null, cur).ConfigureAwait(false); seed = ParseResponse(servers, response, limit); if (seed == null) throw new Exception("Bad packet recieved."); i++; } while ((i < maxIterations) && !seed.Equals("0.0.0.0:0") && !seed.Equals(lastSeed)); return servers; }
private static async Task ConsumeOneAsync(UdpClient client, IPAddress ipAddress, int port) { client.Connect(ipAddress, port); var bytes = Encoding.UTF8.GetBytes(Constants.ClientToServer); var tasks = new[] { client.SendAsync(bytes, bytes.Length), ReceiveAndCheckAsync(client, Constants.ServerToClient) }; await Task.WhenAll(tasks); }
public async Task sendBroadcastBytesAsync(byte[] bytes, int port) { try { if (bytes.Count() <= 0) return; UdpClient trasport = new UdpClient(); trasport.Connect(IPAddress.Broadcast, port); await trasport.SendAsync(bytes, bytes.Length); trasport.Close(); } catch { } }
/// <summary> /// Send data packet asynchronously /// </summary> /// <param name="messageBytes">Data to send</param> /// <param name="sendTo">Remote host to send</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public async Task <int> SendAsync(byte[] messageBytes, IPEndPoint sendTo) { Task <int> ret = null; if (messageBytes == null) { throw new ArgumentNullException(nameof(messageBytes)); } ret = _udpClient.SendAsync(messageBytes, messageBytes.Length, sendTo); OnSendCompleted(); return(await ret.ConfigureAwait(false)); }
protected async Task broadcast(String message, int port) { UdpClient udpClient = new UdpClient(); udpClient.EnableBroadcast = true; udpClient.MulticastLoopback = true; udpClient.ExclusiveAddressUse = false; IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, port); byte[] bytes = Encoding.ASCII.GetBytes(message); await udpClient.SendAsync(bytes, bytes.Length, ip); udpClient.Close(); }
public async Task sendUnicastBytesAsync(byte[] bytes, int port) { try { if (bytes.Count() <= 0) return; UdpClient trasport = new UdpClient(); trasport.Connect("127.0.0.1", port); await trasport.SendAsync(bytes, bytes.Length); trasport.Close(); } catch { } }
public Form1() { InitializeComponent(); UdpClient udpClient = new System.Net.Sockets.UdpClient(19851); //UdpClient udpServer = new System.Net.Sockets.UdpClient(19851); //udpClient.Connect(HOSTADDRESS, 19851); // udpServer.BeginReceive(requestCallbacServer, udpServer); udpClient.BeginReceive(requestCallbacClient, udpClient); Send = new Action <byte[]>(o => { udpClient.SendAsync(o, o.Length, HOSTADDRESS, HOSTPORT); }); }
/// <summary> /// Broadcasts the current game information so that other instances can find players. /// </summary> /// <param name="gameInstance">the game information</param> /// <returns><c>true</c>, if message was sent, <c>false</c> otherwise.</returns> public async Task<bool> BroadcastGameInstanceAsync(NetworkGameInstance gameInstance, CancellationToken ct = default(CancellationToken)) { int bytesSent = 0; var json = gameInstance.ToJsonString (); using (var udpClient = new UdpClient ()) { udpClient.EnableBroadcast = true; var recipient = new IPEndPoint (IPAddress.Broadcast, this.Port); var data = Encoding.UTF8.GetBytes (json); bytesSent = await udpClient.SendAsync (data, data.Length, recipient); udpClient.Close (); } return bytesSent == json.Length; }
public async Task SendMessageAsync(string strMessage) { UdpClient objClient = null; try { objClient = new UdpClient(); byte[] btarrMessage = Encoding.UTF8.GetBytes(strMessage); await objClient.SendAsync(btarrMessage, btarrMessage.Length, RemoteEndPoint); } catch(Exception ex) { MessageBox.Show("SendMessageAsync " + ex.Message); } finally { if(objClient != null) { objClient.Close(); } } }
/// <summary> /// Sending an announcement every 3 seconds until the token is cancelled. /// </summary> /// <returns>The async.</returns> /// <param name="token">Token.</param> public async Task BeginAnnouncingAsync (int port, CancellationToken token) { var data = Encoding.UTF8.GetBytes (Header + port); var client = new UdpClient (AddressFamily.InterNetwork); client.MulticastLoopback = true; client.JoinMulticastGroup (BroadcastEndpoint.Address); token.Register (() => client.Close ()); try { while (true) { await client.SendAsync (data, data.Length, BroadcastEndpoint).ConfigureAwait (false); await Task.Delay (TimeSpan.FromSeconds (1), token).ConfigureAwait (false); } } catch (ObjectDisposedException) { token.ThrowIfCancellationRequested (); throw; } }
public static void Main(string[] args) { PrintMessage("Holiday console UDP app"); var udpClient = new UdpClient(9988); try { udpClient.Connect("192.168.0.22", 9988); var sendBytes = new byte[160]; sendBytes.InitializeArrayValues(); // note first 10 bytes are ignored; set these to zero just in case. for (int i = 0; i < 6000; i++) { for (int j = 10; j < 160; j++) { var bytes = new byte[1]; rand.NextBytes(bytes); sendBytes[j] = bytes[0]; } var x = udpClient.SendAsync(sendBytes, sendBytes.Length).Result; Thread.Sleep(TimeSpan.FromSeconds(0.1)); } udpClient.Close(); PrintMessage("All finished. Press Return to continue."); Console.ReadLine(); } catch (Exception) { } }
private static bool IsBrowserAlive(string browserHostname) { const int DefaultBrowserPort = 1434; const int sendTimeout = 1000; const int receiveTimeout = 1000; const byte ClntUcastEx = 0x03; byte[] requestPacket = new byte[] { ClntUcastEx }; byte[] responsePacket = null; using (UdpClient client = new UdpClient(AddressFamily.InterNetwork)) { try { Task<int> sendTask = client.SendAsync(requestPacket, requestPacket.Length, browserHostname, DefaultBrowserPort); Task<UdpReceiveResult> receiveTask = null; if (sendTask.Wait(sendTimeout) && (receiveTask = client.ReceiveAsync()).Wait(receiveTimeout)) { responsePacket = receiveTask.Result.Buffer; } } catch { } } return responsePacket != null && responsePacket.Length > 0; }
public static Task<List<Tuple<string, IPEndPoint>>> SearchForDevices(TimeSpan? searchTime = null) { TimeSpan timeOut = searchTime ?? new TimeSpan(0, 0, 10); return Task.Run(async () => { List<Tuple<string, IPEndPoint>> result = new List<Tuple<string, IPEndPoint>>(); IPEndPoint groupEP = new IPEndPoint(IPAddress.Broadcast, UdpPackge); var udpClient = new UdpClient(); string welcome = "Hello, are you there?"; var data = Encoding.ASCII.GetBytes(welcome); udpClient.SendAsync(data, data.Length, groupEP); // TODO await? var token = new CancellationTokenSource(); token.CancelAfter(timeOut); while (!token.IsCancellationRequested) { try { var receiveBytes = await udpClient.ReceiveAsync().WithCancellation(token.Token).ConfigureAwait(false); var message = Encoding.ASCII.GetString(receiveBytes.Buffer); logger.Info("Report back {0}.", message); var messageSplit = message.Split(';'); var endPoint = new IPEndPoint(IPAddress.Parse(messageSplit[1]), int.Parse(messageSplit[2])); result.Add(new Tuple<string, IPEndPoint>(messageSplit[0], endPoint)); } catch (Exception exp) { logger.Error(exp, "Error while parsing UDP report back."); } } return result; }); }
async Task NetworkRequestAsync(byte[] requestBytes, TimeSpan scanTime, int retries, int retryDelayMilliseconds, Action<string, byte[]> onResponse, System.Net.NetworkInformation.NetworkInterface adapter, CancellationToken cancellationToken) { // http://stackoverflow.com/questions/2192548/specifying-what-network-interface-an-udp-multicast-should-go-to-in-net #if !XAMARIN if (!adapter.GetIPProperties().MulticastAddresses.Any()) return; // most of VPN adapters will be skipped #endif if (!adapter.SupportsMulticast) return; // multicast is meaningless for this type of connection if (OperationalStatus.Up != adapter.OperationalStatus) return; // this adapter is off or not connected if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback) return; // strip out loopback addresses var p = adapter.GetIPProperties().GetIPv4Properties(); if (null == p) return; // IPv4 is not configured on this adapter var ipv4Address = adapter.GetIPProperties().UnicastAddresses .FirstOrDefault(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address; if (ipv4Address == null) return; // could not find an IPv4 address for this adapter var ifaceIndex = p.Index; Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}"); using (var client = new UdpClient()) { for (var i = 0; i < retries; i++) { #if ANDROID var mlock = wifi.CreateMulticastLock("Zeroconf lock"); #endif try { #if ANDROID mlock.Acquire(); #endif client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(ifaceIndex)); client.ExclusiveAddressUse = false; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, scanTime.Milliseconds); client.ExclusiveAddressUse = false; var localEp = new IPEndPoint(IPAddress.Any, 5353); Debug.WriteLine($"Attempting to bind to {localEp} on adapter {adapter.Name}"); client.Client.Bind(localEp); Debug.WriteLine($"Bound to {localEp}"); var multicastAddress = IPAddress.Parse("224.0.0.251"); var multOpt = new MulticastOption(multicastAddress, ifaceIndex); client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt); Debug.WriteLine("Bound to multicast address"); // Start a receive loop var shouldCancel = false; var recTask = Task.Run(async () => { try { while (!shouldCancel) { var res = await client.ReceiveAsync() .ConfigureAwait(false); onResponse(res.RemoteEndPoint.Address.ToString(), res.Buffer); } } catch (ObjectDisposedException) { } }, cancellationToken); var broadcastEp = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353); Debug.WriteLine($"About to send on iface {adapter.Name}"); await client.SendAsync(requestBytes, requestBytes.Length, broadcastEp) .ConfigureAwait(false); Debug.WriteLine($"Sent mDNS query on iface {adapter.Name}"); // wait for responses await Task.Delay(scanTime, cancellationToken) .ConfigureAwait(false); shouldCancel = true; #if CORECLR client.Dispose(); #else client.Close(); #endif Debug.WriteLine("Done Scanning"); await recTask.ConfigureAwait(false); return; } catch (Exception e) { Debug.WriteLine($"Execption with network request, IP {ipv4Address}\n: {e}"); if (i + 1 >= retries) // last one, pass underlying out throw; } finally { #if ANDROID mlock.Release(); #endif } await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false); } } }
public void SendAsync(byte[] sendMessage, IPEndPoint sendEndPoint) { _udpClient.SendAsync(sendMessage, sendMessage.Length, sendEndPoint); }
public static async Task SendOutcomingAsync(UdpClient server, IPEndPoint clientEndPoint, string message) { var outcomingBytes = Encoding.UTF8.GetBytes(message); await server.SendAsync(outcomingBytes, outcomingBytes.Length, clientEndPoint); }
public async Task SendAsync(byte[] datagram) { await _client.SendAsync(datagram, datagram.Length); }
public static void Main(string[] args) { // X:\jsc.svn\examples\java\android\Test\TestUDPSend\TestUDPSend\ApplicationActivity.cs // 2012desktop? System.Console.WriteLine( typeof(object).AssemblyQualifiedName ); // X:\jsc.svn\examples\java\Test\TestNestedTypeImport\TestNestedTypeImport\Class1.cs Action goo = async delegate { // z:\jsc.svn\examples\javascript\chrome\apps\ChromeUDPSendAsync\ChromeUDPSendAsync\Application.cs #region xml var nmessage = "hello world"; var Host = ""; var PublicPort = ""; var message = new XElement("string", new XAttribute("c", "" + 1), new XAttribute("n", nmessage), "Visit me at " + Host + ":" + PublicPort ).ToString(); #endregion var data = Encoding.UTF8.GetBytes(message); //creates a variable b of type byte Console.WriteLine("hi from goo"); var socket = new UdpClient(); #if FEnableBroadcast socket.EnableBroadcast = true; // bind? // http://stackoverflow.com/questions/13691119/chrome-packaged-app-udp-sockets-not-working // chrome likes 0 too. var port = 0; // where is bind async? socket.Client.Bind( // 192.168.43.12 //new IPEndPoint(IPAddress.Any, port: 40000) new IPEndPoint(IPAddress.Parse("192.168.43.12"), port) ); // //Additional information: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied #endif //socket.Connect( // "127.0.0.1", 40804 // ); // X:\jsc.svn\examples\javascript\chrome\apps\ChromeUDPNotification\ChromeUDPNotification\Application.cs var s = await socket.SendAsync( data, data.Length, //, //hostname: "239.1.2.3", //hostname: "127.0.0.1", //hostname: "217.71.46.50", hostname: "192.168.43.252", port: 8080 ); //socket.ReceiveAsync //socket.Close(); }; goo(); CLRProgram.CLRMain(); }
public async Task NetworkRequestAsync(byte[] requestBytes, TimeSpan scanTime, int retries, int retryDelayMilliseconds, Action<string, byte[]> onResponse, CancellationToken cancellationToken) { using (var client = new UdpClient()) { for (var i = 0; i < retries; i++) { #if ANDROID var mlock = wifi.CreateMulticastLock("Zeroconf lock"); #endif try { #if ANDROID mlock.Acquire(); #endif var localEp = new IPEndPoint(IPAddress.Any, 5353); // There could be multiple adapters, get the default one uint index = 0; #if XAMARIN const int ifaceIndex = 0; #else GetBestInterface(0, out index); var ifaceIndex = (int)index; #endif client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)IPAddress.HostToNetworkOrder(ifaceIndex)); client.ExclusiveAddressUse = false; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, scanTime.Milliseconds); client.ExclusiveAddressUse = false; client.Client.Bind(localEp); var multicastAddress = IPAddress.Parse("224.0.0.251"); var multOpt = new MulticastOption(multicastAddress, ifaceIndex); client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt); Debug.WriteLine("Bound to multicast address"); // Start a receive loop var shouldCancel = false; var recTask = Task.Run(async () => { try { while (!shouldCancel) { var res = await client.ReceiveAsync() .ConfigureAwait(false); onResponse(res.RemoteEndPoint.Address.ToString(), res.Buffer); } } catch (ObjectDisposedException) { } }, cancellationToken); var broadcastEp = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353); await client.SendAsync(requestBytes, requestBytes.Length, broadcastEp) .ConfigureAwait(false); Debug.WriteLine("Sent mDNS query"); // wait for responses await Task.Delay(scanTime, cancellationToken) .ConfigureAwait(false); shouldCancel = true; client.Close(); Debug.WriteLine("Done Scanning"); await recTask.ConfigureAwait(false); return; } catch (Exception e) { Debug.WriteLine("Execption: ", e); if (i + 1 >= retries) // last one, pass underlying out throw; } finally { #if ANDROID mlock.Release(); #endif } await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false); } } }
public async Task SendDataAsync(byte[] data, CancellationToken cancellationToken) { await _client.SendAsync(data, data.Length); }
public async Task SendWakeOnLanCommand() { const int payloadSize = 102; WolConfiguration wolConfig = _configurationManager.Configuration.WakeOnLanConfiguration; if (wolConfig == null) { return; } _logger.Log(LogSeverity.Info, String.Format("Sending Wake on LAN signal to {0}", _configurationManager.Configuration.ServerHostName)); //Send magic packets to each address foreach (string macAddress in wolConfig.HostMacAddresses) { byte[] macBytes = PhysicalAddress.Parse(macAddress).GetAddressBytes(); _logger.Log(LogSeverity.Debug, String.Format("Sending magic packet to {0}", macAddress)); //Construct magic packet var payload = new byte[payloadSize]; Buffer.BlockCopy(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, 0, payload, 0, 6); for (int i = 1; i < 17; i++) { Buffer.BlockCopy(macBytes, 0, payload, 6*i, 6); } //Send packet LAN using (var udp = new UdpClient()) { try { udp.Connect(IPAddress.Broadcast, wolConfig.Port); await udp.SendAsync(payload, payloadSize); } catch (Exception ex) { _logger.Error(String.Format("Magic packet send failed: {0}", ex.Message)); } } //Send packet WAN using (var udp = new UdpClient()) { try { udp.Connect(_configurationManager.Configuration.ServerHostName, wolConfig.Port); await udp.SendAsync(payload, payloadSize); } catch (Exception ex) { _logger.Error(String.Format("Magic packet send failed: {0}", ex.Message)); } } } }
public void SendAsync(byte[] datagram, int bytes) { Client.SendAsync(datagram, bytes, _server); }
public async Task<RadiusPacket> SendAndReceivePacket(RadiusPacket packet, int retries = DEFAULT_RETRIES) { using (UdpClient udpClient = new UdpClient()) { udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _SocketTimeout); try { IPAddress hostIP; if (IPAddress.TryParse(_HostName, out hostIP)) udpClient.Connect(hostIP, (int) _AuthPort); else udpClient.Connect(_HostName, (int) _AuthPort); } catch (SocketException e) { int hr = Marshal.GetHRForException(e); string hexValue = hr.ToString("X"); //The requested name is valid, but no data of the requested type was found if (hexValue == "80004005") return null; } var endPoint = (IPEndPoint)udpClient.Client.RemoteEndPoint; int numberOfAttempts = 0; do { await udpClient.SendAsync(packet.RawData, packet.RawData.Length); try { // Using the synchronous method for the timeout features var result = udpClient.Receive(ref endPoint); RadiusPacket receivedPacket = new RadiusPacket(result); if (receivedPacket.Valid && VerifyAuthenticator(packet, receivedPacket)) return receivedPacket; } catch (SocketException) { //Server isn't responding } numberOfAttempts++; } while (numberOfAttempts < retries); } return null; }
private async Task InitialConnection() { try { _udp = new UdpClient(Params.port); _udp.Connect(VoiceEndpoint.Replace(":80", ""), Params.port); VoiceDebugLogger.Log($"Initialized UDP Client at {VoiceEndpoint}"); byte[] packet = new byte[70]; packet[0] = (byte)((Params.ssrc >> 24) & 0xFF); packet[1] = (byte)((Params.ssrc >> 16) & 0xFF); packet[2] = (byte)((Params.ssrc >> 8) & 0xFF); packet[3] = (byte)((Params.ssrc >> 0) & 0xFF); await _udp.SendAsync(packet, 70).ConfigureAwait(false); VoiceDebugLogger.Log("Sent ssrc packet."); UdpReceiveResult resultingMessage = await _udp.ReceiveAsync().ConfigureAwait(false); VoiceDebugLogger.Log("Received IP packet, reading.."); await SendOurIP(GetIPAndPortFromPacket(resultingMessage.Buffer)).ConfigureAwait(false); } catch(Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("[UDP Client Error]: "); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(ex.Message); } }
public void Handler(WebServiceHandler h) { if (advertise == null) { // X:\jsc.svn\examples\javascript\Test\TestWebMethodIPAddress\TestWebMethodIPAddress\ApplicationWebService.cs #region HostUri var Referer = h.Context.Request.Headers["Referer"]; if (Referer == null) Referer = "any"; var HostUri = new { Host = h.Context.Request.Headers["Host"].TakeUntilIfAny(":"), Port = h.Context.Request.Headers["Host"].SkipUntilOrEmpty(":") }; #endregion Console.WriteLine(new { HostUri }); //compiled! launching server! please wait... //20426 -> 17094 //http://192.168.43.252:20426 //> 0001 0x0163 bytes //{ HostUri = { Host = 192.168.43.252, Port = 20426 } } // https://managedupnp.codeplex.com/ // http://www.fluxbytes.com/csharp/upnp-port-forwarding-the-easy-way/ // upnp ? advertise = async delegate { var message = new XElement("string", new XAttribute("c", "" + 1), "Visit me at " + HostUri.Host + ":" + HostUri.Port ).ToString(); //Console.WriteLine(new { HostUri }); Console.WriteLine(new { message }); // android send // X:\jsc.internal.svn\compiler\jsc.meta\jsc.meta\Library\Templates\Java\InternalAndroidWebServiceActivity.cs // chrome send // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServer\ChromeTCPServer\Application.cs // clr send // X:\jsc.svn\market\Abstractatech.Multicast\Abstractatech.Multicast\Library\MulticastListener.cs // new clr send: var port = new Random().Next(16000, 40000); var socket = new UdpClient(); socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); socket.ExclusiveAddressUse = false; socket.EnableBroadcast = true; var loc = new IPEndPoint(IPAddress.Any, port); socket.Client.Bind(loc); // already bound //socket.JoinMulticastGroup(IPAddress.Parse("239.1.2.3"), 30); //var remote = new IPEndPoint(IPAddress.Parse("239.1.2.3"), 40404); //socket.Connect(remote); var data = Encoding.UTF8.GetBytes(message.ToString()); //creates a variable b of type byte // //Additional information: Cannot send packets to an arbitrary host while connected. var result = await socket.SendAsync(data, data.Length, "239.1.2.3", 40404); //var result = await socket.SendAsync(data, data.Length); socket.Close(); }; advertise(); } }
public async Task<IEnumerable<Server>> GetServers( MasterServerRegion region = MasterServerRegion.All, params MasterServerFilter[] masterServerFilters) { var servers = new List<Server>(); using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0))) { client.Connect(_steamSteamIpAddress, _steamSteamPort); string thisServer = null; while (thisServer != FIRST_AND_LAST_SERVER) { var requestPacket = CreateRequestPacket(thisServer ?? FIRST_AND_LAST_SERVER, region, masterServerFilters); await client.SendAsync(requestPacket, requestPacket.Length); var response = await client.ReceiveAsync(); var responseData = response.Buffer.ToList(); for (int i = HEADER_BYTES_LENGTH; i < responseData.Count; i++) { var ip = string.Join(".", responseData.GetRange(i, 4).ToArray()); int port = responseData[i + 4] << 8 | responseData[i + 5]; thisServer = string.Format("{0}:{1}", ip, port); if (thisServer != FIRST_AND_LAST_SERVER) { servers.Add(new Server(new IPEndPoint(IPAddress.Parse(ip), port))); } i += 5; } } } return servers; }
public static async Task Start() { var client = new UdpClient(1812); var serializer = new RadiusPacketSerializer(); while (true) { try { var result = await client.ReceiveAsync(); var request = serializer.Read(result.Buffer); Console.WriteLine(request.Dump()); if (request.Code == RadiusPacketCode.AccessRequest) { var password = (RadiusBinaryAttribute)request.Attributes.FirstOrDefault(a => a.Type == RadiusAttributeType.UserPassword); var code = ((password == null) || (string.Compare(RadiusPacketSerializer.DecodePassword(Secret, request.Authenticator, password.Value), Password, StringComparison.InvariantCulture) != 0)) ? RadiusPacketCode.AccessReject : RadiusPacketCode.AccessAccept; var response = new RadiusPacket { Code = code, Identifier = request.Identifier, Authenticator = request.Authenticator }; var buffer = serializer.Write(response); await client.SendAsync(buffer, buffer.Length, result.RemoteEndPoint); } } catch (Exception ex) { Console.WriteLine(ex); } } }
public async Task<ServerRulesResult> GetServerRules() { using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0))) { client.Connect(EndPoint); var requestPacket = new List<byte>(); requestPacket.AddRange(new Byte[] {0xFF, 0xFF, 0xFF, 0xFF, 0x56}); requestPacket.AddRange(BitConverter.GetBytes(-1)); await client.SendAsync(requestPacket.ToArray(), requestPacket.ToArray().Length); UdpReceiveResult response = await client.ReceiveAsync(); List<byte> responseData = response.Buffer.ToList(); requestPacket.Clear(); requestPacket.AddRange(new Byte[] {0xFF, 0xFF, 0xFF, 0xFF, 0x56}); requestPacket.AddRange(responseData.GetRange(5, 4)); await client.SendAsync(requestPacket.ToArray(), requestPacket.ToArray().Length); response = await client.ReceiveAsync(); return ServerRulesResult.Parse(response.Buffer); } }
private async Task<ReceiveDataInfo> ReceiveDataAsync(ServerAddress address, byte[] data, CancellationToken ct, params char[] header) { var udpClient = new UdpClient(); var ipAddr = IPAddress.Parse(address.Ip); try { udpClient.Connect(ipAddr, address.Port); var sendTime = DateTime.Now; await udpClient.SendAsync(data, data.Length); Packet packet = null; return await Task.Run(async () => { while (true) { var clientResult = await udpClient.ReceiveAsync().WithCancellation(ct); var remoteIp = clientResult.RemoteEndPoint.Address.ToString(); var remotePort = clientResult.RemoteEndPoint.Port; var receiveDate = DateTime.Now; var packetReader = new PacketReader(clientResult.Buffer); var packetheader = packetReader.ReadLong(); if (packet == null) { packet = engineFactory.CreatePacket(packetheader); } packet.AddData(clientResult.Buffer); if (packet.IsCompleted) { var messageReader = new PacketReader(packet.Payload); var messageheader = messageReader.ReadByte(); var messageHeaderChar = Convert.ToChar(messageheader); if (header.Contains(messageHeaderChar)) { var result = new ReceiveDataInfo { Ping = (int)(DateTime.Now - sendTime).TotalMilliseconds, Data = packet.Payload, MessageHeaderChar = messageHeaderChar, }; return result; } } } }); } catch { throw new OperationCanceledException(); } finally { udpClient.Close(); } }
static async Task ServerAsync(CancellationToken ct) { throw new ApplicationException("died"); var client = new UdpClient(5555); var request = new byte[0]; while (!ct.IsCancellationRequested) { await client.SendAsync(request, request.Length); var response = await client.ReceiveAsync(); } }
public async Task<ServerInfoResult> GetServerInfo() { using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0))) { client.Connect(EndPoint); var requestPacket = new List<byte>(); requestPacket.AddRange(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF}); requestPacket.Add(0x54); requestPacket.AddRange(Encoding.ASCII.GetBytes("Source Engine Query")); requestPacket.Add(0x00); await client.SendAsync(requestPacket.ToArray(), requestPacket.ToArray().Length); UdpReceiveResult response = await client.ReceiveAsync(); return ServerInfoResult.Parse(response.Buffer); } }
private async void FindServer(TaskCompletionSource<IPEndPoint> taskCompletionSource, int timeout) { // Create a udp client var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort())); client.Client.ReceiveTimeout = timeout; // Construct the message the server is expecting var bytes = Encoding.UTF8.GetBytes("who is MediaBrowserServer?"); // Send it - must be IPAddress.Broadcast, 7359 var targetEndPoint = new IPEndPoint(IPAddress.Broadcast, 7359); // Send the broadcast await client.SendAsync(bytes, bytes.Length, targetEndPoint).ConfigureAwait(false); try { // Get a result back var result = await client.ReceiveAsync().ConfigureAwait(false); if (result.RemoteEndPoint.Port == targetEndPoint.Port) { // Convert bytes to text var text = Encoding.UTF8.GetString(result.Buffer); // Expected response : MediaBrowserServer|192.168.1.1:1234 // If the response is what we're expecting, proceed if (text.StartsWith("mediabrowserserver", StringComparison.OrdinalIgnoreCase)) { text = text.Split('|')[1]; var vals = text.Split(':'); var endpoint = new IPEndPoint(IPAddress.Parse(vals[0]), int.Parse(vals[1])); taskCompletionSource.SetResult(endpoint); return; } } taskCompletionSource.SetException(new ArgumentException("Unexpected response")); } catch (SocketException ex) { taskCompletionSource.SetException(ex); } }