public DateTime GetTime() { try { // NTPサーバへの接続用UDP生成 var ip = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); var udp = new System.Net.Sockets.UdpClient(ip); // NTPサーバへのリクエスト送信 var sendData = new Byte[48]; sendData[0] = 0xB; udp.Send(sendData, 48, "time.windows.com", 123); // NTPサーバから日時データ受信 var receiveData = udp.Receive(ref ip); // 1900年1月1日からの経過秒数計算 var totalSeconds = (long)( receiveData[40] * Math.Pow(2, (8 * 3)) + receiveData[41] * Math.Pow(2, (8 * 2)) + receiveData[42] * Math.Pow(2, (8 * 1)) + receiveData[43]); var utcTime = new DateTime(1900, 1, 1).AddSeconds(totalSeconds); // 協定世界時 (UTC) からローカルタイムゾーンへの変更 var localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo.Local); return(localTime); } catch { return(System.DateTime.Now); } }
//UDPパケットを受け付け開始 private async Task StartReceiveAudioPacketAsync(BufferedWaveProvider provider) { //G.722コーデックを用意 var codec = new NAudio.Codecs.G722Codec(); var codecState = new NAudio.Codecs.G722CodecState(64000, NAudio.Codecs.G722Flags.None); //UdpClientを作成し、ローカルエンドポイントにバインドする var localEP = new IPEndPoint(IPAddress.Any, LocalPort); using (var udp = new System.Net.Sockets.UdpClient(localEP)) { IPEndPoint remoteEP = null; for (;;) { //データを受信する while (udp.Available > 0) { byte[] rcvBytes = udp.Receive(ref remoteEP); short[] bufferedData = new short[350]; int bufferdLength = codec.Decode(codecState, bufferedData, rcvBytes, rcvBytes.Length); byte[] bufferdBytes = ConvertShortTo16Bit(bufferedData, bufferdLength); //バッファに追加 provider.AddSamples(bufferdBytes, 0, bufferdBytes.Length); } await Task.Delay(10); } } }
static void RunServer() { System.Net.IPEndPoint anyIP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); System.Net.Sockets.UdpClient udpListener = new System.Net.Sockets.UdpClient(514); byte[] bReceive; string sReceive; string sourceIP; /* Main Loop */ /* Listen for incoming data on udp port 514 (default for SysLog events) */ while (true) { try { bReceive = udpListener.Receive(ref anyIP); // Convert incoming data from bytes to ASCII sReceive = System.Text.Encoding.ASCII.GetString(bReceive); // Get the IP of the device sending the syslog sourceIP = anyIP.Address.ToString(); // Start a new thread to handle received syslog event new System.Threading.Thread(new logHandler(sourceIP, sReceive).handleLog).Start(); } catch (System.Exception ex) { System.Console.WriteLine(ex.ToString()); } } // Whend } // End Sub Main
static void Main(string[] args) { //specify char code System.Text.Encoding enc = System.Text.Encoding.UTF8; //locak port number to bind int localPort = 9750; //binding localPort System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient(localPort); //データを受信する System.Net.IPEndPoint remoteEP = null; while (true) { byte[] rcvBytes = udp.Receive(ref remoteEP); string rcvMsg = enc.GetString(rcvBytes); OutputString(string.Format("received:{0}", rcvMsg)); OutputString(string.Format("source address:{0}/port:{1}", remoteEP.Address, remoteEP.Port)); } //close UDP connection udp.Close(); //Console.ReadLine(); }
static void RunServer() { System.Net.IPEndPoint anyIP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); System.Net.Sockets.UdpClient udpListener = new System.Net.Sockets.UdpClient(514); byte[] bReceive; string sReceive; string sourceIP; /* Main Loop */ /* Listen for incoming data on udp port 514 (default for SysLog events) */ while (true) { try { bReceive = udpListener.Receive(ref anyIP); // Convert incoming data from bytes to ASCII sReceive = System.Text.Encoding.ASCII.GetString(bReceive); // Get the IP of the device sending the syslog sourceIP = anyIP.Address.ToString(); // Start a new thread to handle received syslog event new System.Threading.Thread(new logHandler(sourceIP, sReceive).handleLog).Start(); } catch (System.Exception ex) { System.Console.WriteLine(ex.ToString()); } } // Whend } // End Sub Main
/// <summary> /// Defines the entry point of the application. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { if (args[0] != null) { logFile = args[0]; } else { System.Console.WriteLine("Missing Argument (logfile)"); } // Main processing Thread System.Threading.Thread handler = new System.Threading.Thread(new System.Threading.ThreadStart(HandleMessage)) { IsBackground = true }; handler.Start(); /* Main Loop */ /* Listen for incoming data on udp port 514 (default for SysLog events) */ while (queueing || messageQueue.Count != 0) { try { anyIP.Port = 514; // https://www.real-world-systems.com/docs/logger.1.html // sudo apt-get install bsdutils // logger -p auth.notice "Some message for the auth.log file" // logger -p auth.notice "Some message for the auth.log file" --server 127.0.0.1 // Receive the message byte[] bytesReceive = udpListener.Receive(ref anyIP); // push the message to the queue, and trigger the queue Data.Message msg = new Data.Message { MessageText = System.Text.Encoding.ASCII.GetString(bytesReceive), RecvTime = System.DateTime.Now, SourceIP = anyIP.Address }; lock (messageQueue) { messageQueue.Enqueue(msg); } messageTrigger.Set(); } catch (System.Exception ex) { // ToDo: Add Error Handling System.Console.WriteLine(ex.Message); } } }
public ReplyData GetReply(InputData data) { byte[] inputBuffer = ByteArray.CreateFrom(data); server.Send(inputBuffer, inputBuffer.Length); var peerAddress = new IPEndPoint(IPAddress.Any, 0); var message = replySocket.Receive(ref peerAddress); var replyData = message.ConvertTo <ReplyData>(); return(replyData); }
public static NTPData Test(IPAddress ntpServer) { var data = MarshalExtend.GetData(new NTPData()); var udp = new System.Net.Sockets.UdpClient(); udp.Send(data, data.Length, new IPEndPoint(ntpServer, 123)); var ep = new IPEndPoint(IPAddress.Any, 0); var replyData = udp.Receive(ref ep); return MarshalExtend.GetStruct<NTPData>(replyData, replyData.Length); }
public void TestMethod1() { var udpClient = new System.Net.Sockets.UdpClient(); var endPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("194.87.95.140"), 5150); udpClient.Send(new byte[] { 0x0a, 0x00 }, 2, endPoint); var bytesReceived = udpClient.Receive(ref endPoint); udpClient.Send(new byte[] { 0x00, 0x00, 0x27, 0x00, 0x05 }, 5, endPoint); //TODO: Sometimes e3 01 00 and rest is contained in one package and otherwise bytesReceived = udpClient.Receive(ref endPoint); //bytesReceived = udpClient.Receive(ref endPoint); var bytesToSent = new byte[] { 0x00, 0x80, 0x02, 0xa0, 0x04, 0x07 }. Concat(bytesReceived.Skip(9).Take(20)). Concat(new byte[] { 0x4f, 0x50, 0xc9, 0x6f, 0xad, 0x4e, 0x21, 0xba, 0xc7, 0x5c, 0x37, 0xdf, 0x9f, 0x45, 0x7e, 0x96, 0x21, 0xa8, 0x69, 0x60, 0x23, 0x67, 0xcc, 0x10, 0xf9, 0xb2, 0xeb, 0x31, 0x87, 0xc3, 0xe7, 0x1f }). ToArray(); udpClient.Send(bytesToSent, bytesToSent.Length, endPoint); bytesReceived = udpClient.Receive(ref endPoint); }
static void Main(string[] args) { System.Net.Sockets.UdpClient server = new System.Net.Sockets.UdpClient(15000); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); byte[] data = new byte[1024]; data = server.Receive(ref sender); server.Close(); string stringData = Encoding.ASCII.GetString(data, 0, data.Length); Console.WriteLine("Respondiendo desde " + sender.Address + Environment.NewLine + "Mensaje: " + stringData); Console.ReadLine(); }
public static NTPData Test(IPAddress ntpServer) { var data = MarshalExtend.GetData(new NTPData()); var udp = new System.Net.Sockets.UdpClient(); udp.Send(data, data.Length, new IPEndPoint(ntpServer, 123)); var ep = new IPEndPoint(IPAddress.Any, 0); var replyData = udp.Receive(ref ep); return(MarshalExtend.GetStruct <NTPData>(replyData, replyData.Length)); }
public void Receive(string outputFile = "", bool outputStatistics = false) { if (outputFile == null) { throw new ArgumentNullException(nameof(outputFile)); } if (outputFile == string.Empty) { return; } var writer = new StreamWriter(outputFile) { AutoFlush = true }; var lastPacket = new DataPacket(0, new TimeSpan()); do { var receivedData = _server.Receive(ref _listenEndPoint); try { var packet = JsonConvert.DeserializeObject <DataPacket>(Encoding.ASCII.GetString(receivedData)); packet.ReceiveDateTime = DateTime.Now; var packetStats = new PacketStatistics(packet, lastPacket); writer.WriteLine(outputStatistics ? packetStats.ToString() : packet.ToString()); lastPacket = packet; } catch (Exception) { // ignored } } while (true); }
static void Main(string[] args) { //var ip = System.Net.IPAddress.Parse("127.0.0.1"); var port = 50002; var server = new System.Net.Sockets.UdpClient(port, System.Net.Sockets.AddressFamily.InterNetwork); Console.WriteLine("udp监听已经启动"); while (true) { var remote = new System.Net.IPEndPoint(System.Net.IPAddress.None, 0); var buffer = server.Receive(ref remote); System.Threading.ThreadPool.QueueUserWorkItem(ReciveMessage, Tuple.Create(buffer, remote)); } }
public void ReceiveLoop() { while (true) { try { Packet packet = new Packet(); packet.buffer = client.Receive(ref packet.ep); this.receive_queue.Enqueue(packet); //System.Console.Out.WriteLine("Enqueued a packet from: " + packet.ep.Address); } catch (Exception e) { System.Console.Error.WriteLine(e); } } }
static void Main(string[] args) { t = new System.Timers.Timer(); t.Interval = 1000; t.Elapsed += T_Elapsed; try { System.Net.IPEndPoint groupEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any,5001); System.Net.Sockets.UdpClient listener = new System.Net.Sockets.UdpClient(groupEP); Console.WriteLine("\rPackets Recd: "); Console.WriteLine("\rTime: " + " Seconds"); Console.WriteLine("\rMoving Avg:\t Bytes/sec"); Console.WriteLine("\rTotal Avg:\t Bytes/sec"); Console.WriteLine("\rMax:\t Bytes/sec"); Console.WriteLine("\rMin:\t Bytes/sec"); while (listener.Receive(ref groupEP).Length == 0) {} startTime = DateTime.Now; bytesRec = 0; t.Start(); byte[] data; while (true) { data = listener.Receive(ref groupEP); bytesRec += data.Length; } } catch (Exception ex) { Console.WriteLine("FATAL EXCEPTION!"); Console.WriteLine(ex.Message); Console.WriteLine("Press enter to exit"); Console.ReadLine(); } }
public void Start() { Task.Factory.StartNew(() => { var peerAddress = new IPEndPoint(IPAddress.Any, 0); replySocket.Connect(Program.ClientIP, 16001); while (true) { var message = server.Receive(ref peerAddress); var inputData = message.ConvertTo <InputData>(); var reply = ServerLogic.Convert(inputData); var replyBuffer = ByteArray.CreateFrom(reply); replySocket.Send(replyBuffer, replyBuffer.Length); } }); }
static void Main(string[] args) { //バインドするローカルIPとポート番号 string localIpString = "192.168.0.7"; var localAddress = System.Net.IPAddress.Parse(localIpString); // Browsing datagram responses of NetBIOS over TCP/IP int localPort = 138; // Browsing requests of NetBIOS over TCP/IP //int localPort = 137; //指定したアドレスとポート番号を使用して、IPEndPointクラスの新しいインスタンスを初期化 var localEP = new System.Net.IPEndPoint(localAddress, localPort); //インスタンスを初期化し、指定したローカルエンドポイントにバインド var udp = new System.Net.Sockets.UdpClient(localEP); for (; ;) { //データを受信 System.Net.IPEndPoint remoteEP = null; //リモートホストが送信したUDPデータグラムを返す byte[] rcvBytes = udp.Receive(ref remoteEP); //データを文字列に変換 string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes); //受信したデータと送信者の情報を表示 Console.WriteLine("受信したデータ:{0}", rcvMsg); Console.WriteLine("送信元アドレス:{0}/ポート番号:{1}", remoteEP.Address, remoteEP.Port); //"exit"を受信したら終了 if (rcvMsg.Equals("exit")) { break; } } //UdpClientを閉じる udp.Close(); Console.WriteLine("終了しました。"); Console.ReadLine(); }
static void UdpServer(String server, int port) { // UDP 서버 작성 System.Net.Sockets.UdpClient udpServer = new System.Net.Sockets.UdpClient(port); try { //IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); while (true) { Console.WriteLine("수신 대기..."); IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] receiveBytes = udpServer.Receive(ref remoteIpEndPoint); string returnData = System.Text.Encoding.GetEncoding(932).GetString(receiveBytes); // 수신 데이터와 보낸 곳 정보 표사 Console.WriteLine("수신: {0}Bytes {1}", receiveBytes.Length, returnData); Console.WriteLine("보낸 곳 IP=" + remoteIpEndPoint.Address.ToString() + " 포트 번호= " + remoteIpEndPoint.Port.ToString()); // 수신 데이터를 대문자로 변환하여 보낸다. returnData = returnData.ToUpper(); byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(returnData); // UTF8 // 보낸 곳에 답변 Console.WriteLine("답변 데이터: {0}bytes {1}", sendBytes.Length, returnData); udpServer.Send(sendBytes, sendBytes.Length, remoteIpEndPoint); } } catch (Exception e) { Console.WriteLine(e.ToString()); } udpServer.Close(); Console.Read(); }
private void ReceiveProc() { while (threadActive) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes; int resSize = 0; do { try { System.Net.IPEndPoint remoteEP = null; resBytes = udp.Receive(ref remoteEP); resSize = resBytes.Length; } catch (Exception e) { if (LogHandler != null) { LogHandler(this, e.ToString()); } threadActive = false; break; } // 受信したデータを蓄積する ms.Write(resBytes, 0, resSize); } while (resBytes[resSize - 1] != '\n'); // 受信したデータを文字列に変換 System.Text.Encoding enc = System.Text.Encoding.UTF8; string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); // 末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); string[] resMsgList = resMsg.Split('\n'); foreach (var msg in resMsgList) { if (msg.Length != 0) { ReceiveHandler(this, msg); } } } }
void RecieveLoop() { while (true) { System.Net.IPEndPoint remoteEP = null; byte[] rcvBytes = udp.Receive(ref remoteEP); string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes); var msg = Newtonsoft.Json.JsonConvert.DeserializeObject <Message>(rcvMsg); var item = new ListViewItem(DateTime.Now.ToShortTimeString()); item.SubItems.Add(msg.Name); item.SubItems.Add(msg.Body); if (item.Name != System.Environment.UserName) { Invoke(new ListViewEdit(CalcListView), item); //listView1.Items.Add(item);//これだとエラー } } }
public UdpClient(OnDataReceivedHandler OnDataReceived) { System.Net.Sockets.UdpClient rec_socket = new System.Net.Sockets.UdpClient(8815); var endPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8815); this.OnDataReceived += OnDataReceived; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback( (o) => { while (true) { byte[] bytes = rec_socket.Receive(ref endPoint); this.OnDataReceived?.Invoke(bytes); //System.Threading.Thread.Sleep(1); } } )); }
/// 接收数据 private void ReceiveMessage(object obj) { IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0); while (true) { try { if (udpcMiio.Client == null) { return; } if (udpcMiio.Available <= 0) { System.Threading.Thread.Sleep(1000); continue; } byte[] bytRecv = udpcMiio.Receive(ref remoteIpep); string recmes = byteToHexStr(bytRecv); AddMessage(tbInfo, "接收到:" + recmes); if (waitfortoken && (recmes.StartsWith("2131002000000000"))) { waitfortoken = false; if ((recmes.Substring(32).StartsWith("FFFFFFFFFFFFFFFFFFFFF")) || (recmes.Substring(32).StartsWith("000000000000000000000"))) { AddMessage(tbInfo, "Token获取失败,需尝试其它获取方法(如米家App)"); tstamp = Int32.Parse(recmes.Substring(24, 8), System.Globalization.NumberStyles.HexNumber); AddMessage(tbInfo, "获取到DID:" + recmes.Substring(16, 8) + ";和tstamp:" + tstamp); ShowMessage(tbDid, recmes.Substring(16, 8)); continue; } ShowMessage(tbToken, recmes.Substring(32)); ShowMessage(tbDid, recmes.Substring(16, 8)); tstamp = Int32.Parse(recmes.Substring(24, 8), System.Globalization.NumberStyles.HexNumber); AddMessage(tbInfo, "Token & DID 已获取,别忘了检查确认。时间戳:" + recmes.Substring(24, 8)); continue; } tstamp = Int32.Parse(recmes.Substring(24, 8), System.Globalization.NumberStyles.HexNumber); AddMessage(tbInfo, "接收到消息,解密为:" + Decrypt(recmes.Substring(64), tbToken.Text) + ";时间戳:" + recmes.Substring(24, 8)); } catch (Exception ex) { AddMessage(tbInfo, ex.Message); } } }
private void ListenHandler() { var epGroup = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 2425); byte[] buffer = null; while (IsListening) { System.Threading.Thread.Sleep(1000); try { buffer = UdpClient.Receive(ref epGroup); } catch (Exception) { } if (buffer == null || buffer.Length < 1) { continue; } var msg = System.Text.Encoding.Default.GetString(buffer); if (msg.Length > 0) { Owner.Invoke(DgGetMsg, epGroup.Address.ToString(), msg); } } }
static void Udpsend(string host, int port, string uri, string action) { var client = new System.Net.Sockets.UdpClient(); IPEndPoint ep = new IPEndPoint(IPAddress.Parse(host), port); // endpoint where server is listening client.Connect(ep); // send data client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5); // then receive data try { var receivedData = client.Receive(ref ep); } catch (System.Net.Sockets.SocketException e) { Console.WriteLine("Exception: {0}", e.Source); } Console.Write("receive data from " + ep.ToString()); Console.Read(); }
protected virtual void DoRead() { try { if (m_Udp == null) { return; } byte[] recvBuf = m_Udp.Receive(ref m_RecvEndPoint); if (recvBuf == null) { return; } OnThreadBufferProcess(recvBuf, recvBuf.Length); } catch (Exception e) { #if DEBUG UnityEngine.Debug.LogError(e.ToString()); #endif } }
public static void test() { //バインドするローカルIPとポート番号 string localIpString = "0.0.0.0"; System.Net.IPAddress localAddress = System.Net.IPAddress.Parse(localIpString); int localPort = 10001; //UdpClientを作成し、ローカルエンドポイントにバインドする System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(localAddress, localPort); System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient(localEP); for (; ;) { //データを受信する System.Net.IPEndPoint remoteEP = null; byte[] rcvBytes = udp.Receive(ref remoteEP); //データを文字列に変換する string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes); UdpReceiver.udp_time = DateTime.Now; UdpReceiver.udp_flag = true; //"exit"を受信したら終了 if (rcvMsg.Equals("exit")) { break; } } //UdpClientを閉じる udp.Close(); Console.WriteLine("終了しました。"); Console.ReadLine(); }
public static DateTime GetDateTimeNow() { try { var ip = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); var udp = new System.Net.Sockets.UdpClient(ip); var sendData = new Byte[48]; sendData[0] = 0xB; udp.Send(sendData, 48, "time.windows.com", 123); var receiveData = udp.Receive(ref ip); var totalSeconds = (long)( receiveData[40] * Math.Pow(2, (8 * 3)) + receiveData[41] * Math.Pow(2, (8 * 2)) + receiveData[42] * Math.Pow(2, (8 * 1)) + receiveData[43]); var utcTime = new DateTime(1900, 1, 1).AddSeconds(totalSeconds); return(TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo.Local)); } catch (Exception err) { Console.WriteLine(err.Message); return(DateTime.MinValue); } }
private byte[] ReceiveBytes(int timeout, out IPEndPoint endPoint) { byte[] receivedBytes = null; endPoint = null; try { while (isActive && myUdpClient?.Available <= 0 && timeout > 0) { Thread.Sleep(10); timeout -= 10; } if (isActive && myUdpClient?.Available > 0) { receivedBytes = myUdpClient.Receive(ref endPoint); } } catch (Exception err) { Log.Error($"Unexpected exception while receiving datagram: {err.Message} "); } return(receivedBytes); }
// Method public int Authenticate() { DebugOutput("Shared Secret (S): " + pSSecret); DebugOutput("Username: "******"Password: "******" (" + pPassword.Length*8 + " bits)"); /* Aufbau eines Radius Paketes * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Code | Identifier | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * | Authenticator | * | | * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Attributes ... * +-+-+-+-+-+-+-+-+-+-+-+-+- * * * CODE (1 byte): * The type of the Radius Paket. * Pakets with an invalid code will be discarded. * 1 = Access-Request * 2 = Access-Accept * 3 = Access-Reject * 11 = Access-Challenge * 12 = Status-Server (exp.) * 13 = Status-Client (exp.) * 255 = reserved * * IDENTIFIER (1 byte): * Is the same in Request and Reply. * (Random Number from 1..254) * * LENGTH (2 byte): * Length of the paket in BYTE over: * Code, Identifier, Length, Authenticator and Attribute(s) * - Bytes which excess the length, will be cut. * - Pakets smaller then the length will be discarded by the server. * * AUTHENTICATOR (16 byte): * 16-byte random number * Used for the encryption of the user-password * * ATTRIBUTES (dynamic length): * 0 1 2 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- * | Type | Length | Value ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- * * - User Password = Type 2 (String) * A complete Attribute-List: http://www.freeradius.org/rfc/attributes.html * * */ byte pCode = 1; // Access-Request int pResult = 0; Random pRandonNumber = new Random(); byte pIdentifier = Convert.ToByte(pRandonNumber.Next(0, 32000) % 256); pClientIdentifier = pIdentifier; DebugOutput("Identifier (Radius-Request): " + pClientIdentifier); GenerateRA(); //Should be a random number!!! DebugOutput("Request Authenticator (RA): " + Utils.ToHexString(pRA)); // Assemble Attribute User-Name (Type = 1) and put it in the list SetAttribute(1, pUsername); // Assemble Attribute User-Password (Type = 2) and put it in the list SetAttribute(2, Crypto.GeneratePAP_PW(pPassword, pSSecret, pRA)); // Assemble complete Radius Paket: // 1.) Determine the length of the paket (in bytes) // Code, ID & Lenght = 4 Bytes //****************************************************************************** int pAttrLength = 0; foreach (RadiusAttribute pCurrAttr in pAttributeList) { pAttrLength += pCurrAttr.Paket.Length; } //foreach (RadiusAttribute pCurrAttr in pAttributeList) int pLength = 4 + pRA.Length + pAttrLength; //****************************************************************************** int pOffset = 0; // 2.) Creating empty byte Array with the calculated length byte[] pRadiusPaket = new byte[pLength]; // 3.) Copy the paket-parts to the paket // 3.1) the Code from pCode pRadiusPaket[0] = pCode; // 3.2) The identifier from pIdentifier pRadiusPaket[1] = pIdentifier; pOffset = 1; // 3.3) The paket length (2 Byte) // ENDIANESS PROBLEM !!! CAUTION byte[] pPacketLen = Utils.intToByteArray(pLength); Array.Copy(pPacketLen, 0, pRadiusPaket, pOffset + 1, 2); pOffset = pOffset + 2; // 3.4) The RA from pRA //Array.Copy(System.Text.Encoding.ASCII.GetBytes(pRA), 0, pRadiusPaket, pOffset + 1, pRA.Length); Array.Copy(pRA, 0, pRadiusPaket, pOffset + 1, pRA.Length); pOffset = pOffset + pRA.Length; // 3.5) Add Radius Attributes to Paket foreach (RadiusAttribute pCurrAttr in pAttributeList) { Array.Copy(pCurrAttr.Paket, 0, pRadiusPaket, pOffset + 1, pCurrAttr.Paket.Length); pOffset += pCurrAttr.Paket.Length; } // SENDING THE PAKET TO THE REMOTE RADIUS SERVER try { System.Net.Sockets.UdpClient myRadiusClient = new System.Net.Sockets.UdpClient(); myRadiusClient.Client.SendTimeout = pUDPTimeout; myRadiusClient.Client.ReceiveTimeout = UDPTimeout; DebugOutput("Trying to send the Radius-Request to " + pServer + ":" + pRadiusPort.ToString()); myRadiusClient.Ttl = UDP_TTL; myRadiusClient.Connect(pServer, pRadiusPort); myRadiusClient.Send(pRadiusPaket, pRadiusPaket.Length); System.Net.IPEndPoint RemoteIpEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); Byte[] receiveBytes = myRadiusClient.Receive(ref RemoteIpEndPoint); myRadiusClient.Close(); pResult = ProcessServerResponse(receiveBytes); //DebugOutput("Output by ProcessServerResponse: " + Code2Message(pResult) + " (Code = " + pResult.ToString() + ")"); } catch (Exception e) { DebugOutput("Exception Error: " + e.ToString()); pMessage = "Exception Error: " + e.Message; SiAuto.Main.LogError(e.Message); return(-2); } return(pResult); } //public int Authenticate()
/// <summary> /// Receives data. /// </summary> private void InternalBeginReceive() { while (_connected) { if (_udpClient.Available > 0) { var serverIpEndPoint = new IPEndPoint(IPAddress.Any, 2565); byte[] receivedData = _udpClient.Receive(ref serverIpEndPoint); using (var mStream = new MemoryStream(receivedData)) { IBasePackage package = PackageSerializer.Deserialize(mStream); var binaryPackage = package as BinaryPackage; if (binaryPackage != null) { //binary package foreach (IPackageListener subscriber in GetPackageSubscriber(binaryPackage.OriginType)) { subscriber.OnPackageReceived(binaryPackage); } continue; } //system packages var systemPackage = package as NotificationPackage; if (systemPackage != null) { switch (systemPackage.Mode) { case NotificationMode.ClientJoined: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnClientJoined(systemPackage.Connection[0]); } break; case NotificationMode.ClientExited: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnClientExited(systemPackage.Connection[0]); } break; case NotificationMode.ClientList: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnClientListing(systemPackage.Connection); } break; case NotificationMode.TimeOut: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnClientTimedOut(); } break; case NotificationMode.ServerShutdown: for (int i = 0; i <= _clientListeners.Count - 1; i++) { _clientListeners[i].OnServerShutdown(); } break; } } var pingPackage = package as PingPackage; if (pingPackage != null) { //send ping package back Send(pingPackage); } } } else { //no data available Idle(); } } }
// 別スレッド処理(UDP) //IP 192.168.1.209 private void worker_udp_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker bw = (BackgroundWorker)sender; //バインドするローカルポート番号 int localPort = mmFsiUdpPortKV1000SpCam2; // 24410;// broadcast mmFsiUdpPortMT3IDS2; System.Net.Sockets.UdpClient udpc4 = null;; try { udpc4 = new System.Net.Sockets.UdpClient(localPort); } catch (Exception ex) { //匿名デリゲートで表示する //this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() }); ShowRTextFW(ex.ToString()); } //文字コードを指定する System.Text.Encoding enc = System.Text.Encoding.UTF8; //データを送信するリモートホストとポート番号 //string remoteHost = "localhost"; string remoteHost = "192.168.1.10"; // KV1000; int remotePort = 8501; string str; MOTOR_DATA_KV_SP kmd3 = new MOTOR_DATA_KV_SP(); int size = Marshal.SizeOf(kmd3); KV_DATA kd = new KV_DATA(); int sizekd = Marshal.SizeOf(kd); // loop System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, localPort); while (bw.CancellationPending == false) { //データを受信する byte[] rcvBytes = udpc4.Receive(ref remoteEP); if (remoteEP.Address.ToString() == remoteHost && remoteEP.Port == remotePort) { //kd = ToStruct1(rcvBytes); //bw.ReportProgress(0, kd); string rcvMsg = enc.GetString(rcvBytes); str = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff") + "受信したデータ:[" + rcvMsg + "]\n"; ShowRTextFW(str); //this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, str }); } else { string rcvMsg = enc.GetString(rcvBytes); str = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff") + "送信元アドレス:{0}/ポート番号:{1}/Size:{2}\n" + remoteEP.Address + "/" + remoteEP.Port + "/" + rcvBytes.Length + "[" + rcvMsg + "]\n"; ShowRTextFW(str); //this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, str }); } //データを送信する if (cmd_str_f != 0) { //送信するデータを読み込む string sendMsg = cmd_str + "\r";// "test送信するデータ"; byte[] sendBytes = enc.GetBytes(sendMsg); //リモートホストを指定してデータを送信する udpc4.Send(sendBytes, sendBytes.Length, remoteHost, remotePort); cmd_str_f = 0; } } //UDP接続を終了 udpc4.Close(); }
static StackObject *Receive_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Net.IPEndPoint @remoteEP = (System.Net.IPEndPoint) typeof(System.Net.IPEndPoint).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Net.Sockets.UdpClient instance_of_this_method = (System.Net.Sockets.UdpClient) typeof(System.Net.Sockets.UdpClient).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.Receive(ref @remoteEP); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch (ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @remoteEP; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) { ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; } __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if (___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @remoteEP; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @remoteEP); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if (___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @remoteEP; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @remoteEP); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Net.IPEndPoint[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @remoteEP; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); __intp.Free(ptr_of_this_method); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
public static DateTime setNTP() { // NTPサーバへの接続用UDP生成 System.Net.Sockets.UdpClient objSck; System.Net.IPEndPoint ipAny = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); objSck = new System.Net.Sockets.UdpClient(ipAny); // NTPサーバへのリクエスト送信 Byte[] sdat = new Byte[48]; sdat[0] = 0xB; try { objSck.Send(sdat, sdat.GetLength(0), "time.windows.com", 123); } catch (Exception e) { return DateTime.Now; throw; } // NTPサーバから日時データ受信 Byte[] rdat = objSck.Receive(ref ipAny); // 1900年1月1日からの経過時間(日時分秒) long lngAllS; // 1900年1月1日からの経過秒数 long lngD; // 日 long lngH; // 時 long lngM; // 分 long lngS; // 秒 // 1900年1月1日からの経過秒数計算 lngAllS = (long)( rdat[40] * Math.Pow(2, (8 * 3)) + rdat[41] * Math.Pow(2, (8 * 2)) + rdat[42] * Math.Pow(2, (8 * 1)) + rdat[43]); // 1900年1月1日からの経過(日時分秒)計算 lngD = lngAllS / (24 * 60 * 60); // 日 lngS = lngAllS % (24 * 60 * 60); // 残りの秒数 lngH = lngS / (60 * 60); // 時 lngS = lngS % (60 * 60); // 残りの秒数 lngM = lngS / 60; // 分 lngS = lngS % 60; // 秒 // 現在の日時(DateTime)計算 DateTime dtTime = new DateTime(1900, 1, 1); dtTime = dtTime.AddDays(lngD); dtTime = dtTime.AddHours(lngH); dtTime = dtTime.AddMinutes(lngM); dtTime = dtTime.AddSeconds(lngS); // グリニッジ標準時から日本時間への変更 dtTime = dtTime.AddHours(9); // 現在の日時表示 System.Diagnostics.Trace.WriteLine(dtTime); // システム時計の日時設定 return dtTime; }
private void StartListener(object oState) { try { oUDPClient = new System.Net.Sockets.UdpClient(Convert.ToInt32(CDLLReadSetting.ReadSetting("//configuration/appSettings/add[@key='MulticastPort']"))); oUDPClient.Client.ReceiveBufferSize = Convert.ToInt32(CDLLReadSetting.ReadSetting("//configuration/appSettings/add[@key='UDPBufferSize']")); System.Net.IPEndPoint oRemoteIPEndPoint = new System.Net.IPEndPoint( System.Net.IPAddress.Parse(CDLLReadSetting.ReadSetting("//configuration/appSettings/add[@key='MulticastIPAddress']")), 0); oUDPClient.DontFragment = true; oUDPClient.JoinMulticastGroup(System.Net.IPAddress.Parse(CDLLReadSetting.ReadSetting("//configuration/appSettings/add[@key='MulticastIPAddress']"))); while (true) { try { Byte[] arTemp = oUDPClient.Receive(ref oRemoteIPEndPoint); System.IO.MemoryStream oMemoryStream = new System.IO.MemoryStream(arTemp.Length); oMemoryStream.Write(arTemp, 0, arTemp.Length); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter oBinary = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); oMemoryStream.Seek(0, System.IO.SeekOrigin.Begin); ReportLog((Hashtable)oBinary.Deserialize(oMemoryStream)); } catch (System.Threading.ThreadAbortException ex) { Console.Write(ex.Message); //MessageBox.Show(ex.Message); } catch (Exception ex) { Console.Write(ex.Message); //MessageBox.Show(ex.Message); } System.Windows.Forms.Application.DoEvents(); if (oUDPClient.Available == 0) { System.Threading.Thread.Sleep(1); } } } catch (System.Threading.ThreadAbortException ex) { Console.Write(ex.Message); //MessageBox.Show(ex.Message); } catch (Exception ex) { Console.Write(ex.Message); //MessageBox.Show(ex.Message); } }
static void Main(string[] args) { System.Net.Sockets.UdpClient udp = null; Console.WriteLine("プログラムスタート"); //バインドするローカルIPとポート番号 try { string localIpString = "192.168.11.53"; System.Net.IPAddress localAddress = System.Net.IPAddress.Parse(localIpString); int localPort = 7000; //UdpClientを作成し、ローカルエンドポイントにバインドする Console.WriteLine("IP Address = " + localIpString + " Port = " + localPort + " UDPで待っています"); Console.WriteLine(); System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(localAddress, localPort); udp = new System.Net.Sockets.UdpClient(localEP); } catch (Exception) { Console.WriteLine("ネットワークのエラー"); Console.WriteLine("何かキーを押してください"); Console.ReadKey(); Environment.Exit(0); } Word.Application word = null; Document document = null; object filename = System.IO.Directory.GetCurrentDirectory() + @"\out.docx"; for (; ;) { //データを受信する System.Net.IPEndPoint remoteEP = null; byte[] rcvBytes = udp.Receive(ref remoteEP); //データを文字列に変換する string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes); //受信したデータと送信者の情報を表示する Console.WriteLine("受信したデータ:{0}", rcvMsg); Console.WriteLine("送信元アドレス:{0}/ポート番号:{1}", remoteEP.Address, remoteEP.Port); //"open word" if (rcvMsg.Equals("open word\n") && word != null) { // Word アプリケーションオブジェクトを作成 word = new Word.Application(); word.Visible = true; // 新規文書を作成 document = word.Documents.Open(filename); continue; } //"close word" if ((rcvMsg.Equals("close word\n") && word != null)) { //object filename = System.IO.Directory.GetCurrentDirectory() + @"\out.docx"; document.SaveAs2(ref filename); // 文書を閉じる document.Close(); document = null; word.Quit(); word = null; continue; } //"exit"を受信したら終了 if (rcvMsg.Equals("exit\n")) { Console.WriteLine("終了コマンド"); break; } if (word != null) { addTextSample(ref document, WdColorIndex.wdBlack, rcvMsg); } } //UdpClientを閉じる udp.Close(); Console.WriteLine("終了しました。"); Console.ReadLine(); }
/// <summary> /// Accepts clients if available. /// </summary> private void BeginAcceptConnections() { var incommingConnection = new IPEndPoint(IPAddress.Any, 2565); while (IsActive) { try { if (_listener.Available > 0) { byte[] receivedData = _listener.Receive(ref incommingConnection); using (var mStream = new MemoryStream(receivedData)) { IBasePackage package = PackageSerializer.Deserialize(mStream); var udpPackage = package as UdpPackage; if (udpPackage != null) { if (udpPackage.NotifyMode == UdpNotify.Hi) { //notify SendNotificationPackage(NotificationMode.ClientJoined, _connections.ToArray()); //add connection var udpConnection = new UdpConnection(incommingConnection.Address); _connections.Add(udpConnection); // publish the new server list, after a new connection. SendNotificationPackage(NotificationMode.ClientList, _connections.ToArray()); } else //(UdpNotify.Bye) { //notify SendNotificationPackage(NotificationMode.ClientExited, _connections.ToArray()); //remove connection UdpConnection udpConnection = GetConnection(incommingConnection.Address); if (udpConnection != null) { _connections.Remove(udpConnection); // publish the new server list, after a lost connection. SendNotificationPackage(NotificationMode.ClientList, _connections.ToArray()); } } } else { //any other package handle in new void HandlePackage(package); } } } else { //no data available Idle(); } } catch (Exception ex) { _logger.Error(ex.Message); } } }
static int IsExpirationDate() { // NTPサーバへの接続用UDP生成 System.Net.Sockets.UdpClient objSck; System.Net.IPEndPoint ipAny = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); objSck = new System.Net.Sockets.UdpClient(ipAny); // NTPサーバへのリクエスト送信 Byte[] sdat = new Byte[48]; sdat[0] = 0xB; Byte[] rdat = null; try { objSck.Send(sdat, sdat.GetLength(0), "time.windows.com", 123); // NTPサーバから日時データ受信 rdat = objSck.Receive(ref ipAny); } catch (Exception e) { Console.WriteLine(e.ToString()); MessageBox.Show("ネットワークエラー", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); return(99); } finally { objSck.Close(); } // 1900年1月1日からの経過時間(日時分秒) long lngAllS; // 1900年1月1日からの経過秒数 long lngD; // 日 long lngH; // 時 long lngM; // 分 long lngS; // 秒 // 1900年1月1日からの経過秒数計算 lngAllS = (long)( rdat[40] * Math.Pow(2, (8 * 3)) + rdat[41] * Math.Pow(2, (8 * 2)) + rdat[42] * Math.Pow(2, (8 * 1)) + rdat[43]); // 1900年1月1日からの経過(日時分秒)計算 lngD = lngAllS / (24 * 60 * 60); // 日 lngS = lngAllS % (24 * 60 * 60); // 残りの秒数 lngH = lngS / (60 * 60); // 時 lngS = lngS % (60 * 60); // 残りの秒数 lngM = lngS / 60; // 分 lngS = lngS % 60; // 秒 // 現在の日時(DateTime)計算 DateTime dtTime = new DateTime(1900, 1, 1); dtTime = dtTime.AddDays(lngD); dtTime = dtTime.AddHours(lngH); dtTime = dtTime.AddMinutes(lngM); dtTime = dtTime.AddSeconds(lngS); // グリニッジ標準時から日本時間への変更 dtTime = dtTime.AddHours(9); // 現在の日時の比較 return("20171231".CompareTo(dtTime.ToString("yyyyMMdd"))); }