/// <summary> /// 连接某IP的端口 /// </summary> /// <param name="ip">要连接的ip</param> /// <param name="port">要连接的端口</param> /// <returns>连上返回true,否则false</returns> private bool IsConnet(string ip, int port) { bool tcpListen = false; bool udpListen = false;//设定端口状态标识位 System.Net.IPAddress myIpAddress = System.Net.IPAddress.Parse(ip); System.Net.IPEndPoint myIpEndPoint = new System.Net.IPEndPoint(myIpAddress, port); try { System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient(); tcpClient.Connect(myIpEndPoint);//对远程计算机的指定端口提出TCP连接请求 tcpListen = true; } catch { } try { System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(); udpClient.Connect(myIpEndPoint);//对远程计算机的指定端口提出UDP连接请求 udpListen = true; } catch { } if (tcpListen == false || udpListen == false) { return(false); } else { return(true); } }
static void Main(string[] args) { var udpClient = new System.Net.Sockets.UdpClient(); udpClient.Connect(new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 9500)); udpClient.Send(new byte[] { 1, 0, 0, 0, 8 }, 5); Console.ReadLine(); }
static void Main(string[] args) { var udpClient = new System.Net.Sockets.UdpClient(); udpClient.Connect(new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 9500)); udpClient.Send(new byte[] { 1, 0, 0, 0, 8 }, 5); Console.ReadLine(); }
private static void send_packet( string data_package ) { var magic_packet = new System.Net.Sockets.UdpClient( ); try { magic_packet.Connect( System.Net.IPAddress.Broadcast, 9 ); var dgram = hex_string_to_byte( data_package ); magic_packet.Send( dgram, dgram.Length ); magic_packet.Close( ); } catch( Exception e ) { MessageBox.Show( string.Format( "Exception while sending packet: {0}", e.Message ) ); } }
public static System.Net.Sockets.UdpClient GetUdpSender(string ipAddressString, int port) { // TODO: Check System.Net.IPAddress socketIPAddress = System.Net.IPAddress.Parse(ipAddressString); int socketPort = port; System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(); udpClient.JoinMulticastGroup(socketIPAddress); udpClient.Connect(new System.Net.IPEndPoint(socketIPAddress, socketPort)); return(udpClient); }
private void _sendMsg(object param) { byte[] message = (param as byte[]); using (System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient()) { client.Connect(IP, Port); client.Send(message, message.Length); if (Delay != 0) { Thread.Sleep(Delay); } } }
public void Connect(string ipAddress, int sendPort) { try { _client = new System.Net.Sockets.UdpClient(); _server = new IPEndPoint(IPAddress.Parse(ipAddress), sendPort); _client.Connect(_server); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
private static void send_packet(string data_package) { var magic_packet = new System.Net.Sockets.UdpClient( ); try { magic_packet.Connect(System.Net.IPAddress.Broadcast, 9); var dgram = hex_string_to_byte(data_package); magic_packet.Send(dgram, dgram.Length); magic_packet.Close( ); } catch (Exception e) { MessageBox.Show(string.Format("Exception while sending packet: {0}", e.Message)); } }
private void UdpPing(string[] vargs) { string ip = vargs.Length > 1 ? vargs[1] : "127.0.0.1"; int port = vargs.Length > 2 ? int.Parse(vargs[2]) : 8989; using (var client = new System.Net.Sockets.UdpClient()) { var ep = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port); // endpoint where server is listening client.Connect(ep); // send data client.Send(new byte[] { 104, 101, 108, 108, 111, 0 }, 6); } }
private void UPDTest() { udpClient = new System.Net.Sockets.UdpClient(); Byte[] sendBytes = Encoding.ASCII.GetBytes("IN;PU0,0;SP1;PA1000,1000;SP0;NR"); IPAddress targetIP = IPAddress.Parse("10.0.1.27"); IPEndPoint targetEP = new IPEndPoint(targetIP, 85); try { udpClient.Connect(targetEP); udpClient.Send(sendBytes, sendBytes.Length); } catch (Exception ex) { MessageBox.Show(ex.Message, "Fehler!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static System.Net.Sockets.UdpClient GetBroadcastSender(System.Net.IPEndPoint clientEndpoint) { //System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(); //udpClient.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReuseAddress, true); //udpClient.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.Broadcast, true); //udpClient.Client.Bind(clientEndpoint); System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(); udpClient.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReuseAddress, true); udpClient.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.Broadcast, true); udpClient.Connect(clientEndpoint); return(udpClient); }
internal static void SendMagicPacket(byte[] mac) { var magicPacket = Enumerable.Repeat((byte)0xff, 6) .Concat(Enumerable.Range(0, 16).SelectMany(i => mac)) .ToArray(); Console.WriteLine("Sending magic wake-on-lan packet..."); using (var udpClient = new System.Net.Sockets.UdpClient()) { udpClient.Connect(System.Net.IPAddress.Broadcast, 7); // Lucky port. udpClient.Send(magicPacket, magicPacket.Length); } }
static void Main(string[] args) { var ip = System.Net.IPAddress.Parse("127.0.0.1"); var port = 50002; Console.WriteLine("请输入要发送的消息"); var client = new System.Net.Sockets.UdpClient(System.Net.Sockets.AddressFamily.InterNetwork); while (true) { var msg = Console.ReadLine(); client.Connect(ip, port); var buffer = System.Text.UTF8Encoding.UTF8.GetBytes(msg); client.Send(buffer, buffer.Length); } }
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); } }); }
internal static bool IsRCONPortOpen(Gameserver gameserver) { using (System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient()) { try { udpClient.Connect(gameserver.RCON_IP, gameserver.RCON_Port); udpClient.Close(); return(true); } catch (Exception) { return(false); } } }
System.Net.IPEndPoint remoteEP; //! endpoint /// <summary> /// Open Udp socket /// </summary> /// <param name="remoteHost"></param> /// <param name="remotePort"></param> /// <param name="localPort"></param> /// <returns></returns> public int Open(string remoteHost, int remotePort, int localPort) { remote_host = remoteHost; lcl_port = localPort; rmt_port = remotePort; // Create UDP client udp = new System.Net.Sockets.UdpClient(lcl_port); // Enable Broadcast udp.EnableBroadcast = true; // Set remote endpoint remoteEP = new IPEndPoint(IPAddress.Parse(remote_host), rmt_port); udp.Connect(remoteEP); return(0); }
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(); }
private void button1_Click(object sender, EventArgs e) { System.Net.Sockets.UdpClient udpc; int ret; int a, c; byte[] sendbuffer; sendbuffer = new byte[1400]; for (a = 0; a < 100; a++) { sendbuffer[a] = (byte)(a & 255); } udpc = new System.Net.Sockets.UdpClient(13455); udpc.Connect(tosendaddr.Text, System.Convert.ToInt32(tosendport.Text, 10)); c = System.Convert.ToInt32(sendcount.Text, 10); for (a = 0; a < 1 /*c*/; a++) { ret = udpc.Send(sendbuffer, 100); } udpc.Close(); }
private void _sendMsg(object param) { byte[] message = (param as byte[]); using (System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient()) { client.Connect(IP, Port); client.Send(message, message.Length); if (Delay != 0) Thread.Sleep(Delay); } }
public void Connect(IPEndPoint endPoint) { this.EndPoint = endPoint; _snd_socket.Connect(this.EndPoint); }
private static void DoWork() { System.Net.Sockets.UdpClient udpc; System.Net.Sockets.Socket sock; System.Net.IPEndPoint ipe; System.Net.Sockets.UdpClient udpcs; byte[] buffer; int[] receivedblock; int[] differ; int a, c; int timeout; uint sequence_number, sequence_number_next0, sequence_number_next1; int expected; System.IO.FileStream fil; byte[] sendbuffer; uint received_sequence_number, received_packet_number; fil = null; if (save_data == 1) { fil = new System.IO.FileStream("packets.bin", System.IO.FileMode.Create); //,System.IO.FileAccess.Write,System.IO.FileShare.Read,8*1024*1024,System.IO.FileOptions.WriteThrough); } buffer = new byte[1600]; differ = new int[257]; udpc = new System.Net.Sockets.UdpClient(receive_port); ipe = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); receivedblock = new int[2]; receivedblock[0] = receivedblock[1] = receive_count; sequence_number = 0; sequence_number_next0 = sequence_number + 1; sequence_number_next1 = sequence_number + 2; sendbuffer = new byte[1400]; for (a = 0; a < 100; a++) { sendbuffer[a] = (byte)(a & 255); } sendbuffer[0] = (byte)((receive_count - 1) & 255); sendbuffer[1] = (byte)(((receive_count - 1) >> 8) & 255); sendbuffer[2] = (byte)((sequence_number) & 255); sendbuffer[3] = (byte)(((sequence_number) >> 8) & 255); sendbuffer[4] = (byte)(((sequence_number) >> 16) & 255); sendbuffer[5] = (byte)(((sequence_number) >> 24) & 255); sendbuffer[6] = 0; udpcs = new System.Net.Sockets.UdpClient(13455); udpcs.Connect(send_address, send_port); //udpcs.Connect("137.204.48.1", 23456); //udpc.Connect("10.0.0.194", 23455); sock = udpc.Client; sock.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReceiveBuffer, 4 * 1024 * 1024); c = receive_count; first = 1; last = 0; wrap = 0; missing = 0; received = 0; recvlast = 0; while (true) { /*receivedblock[0] = receivedblock[1]; * receivedblock[1] = receive_count;*/ sendbuffer[2] = (byte)((sequence_number) & 255); sendbuffer[3] = (byte)(((sequence_number) >> 8) & 255); sendbuffer[4] = (byte)(((sequence_number) >> 16) & 255); sendbuffer[5] = (byte)(((sequence_number) >> 24) & 255); a = udpcs.Send(sendbuffer, 7); first = 1; timeout = 1; expected = 0; //while (receivedblock[0] != 0) while (expected < receive_count) { //if (running == 2) // break; while (udpc.Available <= 0) { if (timeout > 10000) { break; } if (running > 1) { break; } System.Threading.Thread.Sleep(1); if (first != 1) { timeout++; } if ((timeout % 1000) == 0) { a = udpcs.Send(sendbuffer, 7); } } if (timeout > 10000) { break; } if (running > 1) { break; } timeout = 0; buffer = udpc.Receive(ref ipe); // primi 32 bit numero blocco received_sequence_number = (uint)buffer[0] + (uint)buffer[1] * 256 + (uint)buffer[2] * 256 * 256 + (uint)buffer[3] * 256 * 256 * 256; // poi 16 bit numero pacchetto received_packet_number = (uint)buffer[4] + (uint)buffer[5] * 256; if (first == 1) { last = (ulong)received_sequence_number * (ulong)receive_count + (ulong)received_packet_number; first = 0; } else { now = (ulong)received_sequence_number * (ulong)receive_count + (ulong)received_packet_number; if (now >= last) { diff = now - last; } else { diff = 0xffffffffffffffff - last + now + 1; wrap++; } //differ[diff] |= 128; last = now; missing = missing + diff - 1; } if (received_sequence_number == sequence_number_next0) { if (expected == received_packet_number) { expected++; //fil.Write(buffer, 0, buffer.GetUpperBound(0) + 1); } else { expected = (int)received_packet_number + 1; /*running = 3;*/ } /*receivedblock[0]--;*/ if (save_data == 1) { fil.Write(buffer, 0, buffer.GetUpperBound(0) + 1); } } else if (received_sequence_number == sequence_number_next1) { break; /*receivedblock[1]--;*/ fil.Write(buffer, 0, buffer.GetUpperBound(0) + 1); }/* * else * { * }*/ received++; } if (timeout > 10000) { break; } if (running > 1) { break; } sequence_number++; sequence_number_next0++; sequence_number_next1++; } if (running > 1) { System.Threading.Thread.Sleep(1000); while (udpc.Available > 0) { buffer = udpc.Receive(ref ipe); } sendbuffer[6] = 128; if (running == 3) { sendbuffer[6] |= 64; } a = udpcs.Send(sendbuffer, 7); } udpcs.Close(); udpc.Close(); if (save_data == 1) { fil.Close(); } }
public bool Start() { if (cbStarting != null) cbStarting(null); try { udp = new System.Net.Sockets.UdpClient(); udp.Connect(Host, UDPPort); Message("UDP connected"); } catch { Error("Failed to connect"); udp = null; if (cbStopped != null) KeepRunning = cbStopped(null); return false; } try { com = new System.IO.Ports.SerialPort(); com.BaudRate = 4800; com.Parity = System.IO.Ports.Parity.None; com.StopBits = System.IO.Ports.StopBits.One; com.DataBits = 8; com.ReadBufferSize = 4096; com.ReadTimeout = 1500; com.PortName = ComPort; com.Open(); Message("COM open"); } catch { Error("Failed to open com"); udp = null; com = null; if (cbStopped != null) cbStopped(null); return false; } if (cbStarted != null) cbStarted(""); KeepRunning = true; return true; }
/// <summary> /// Start transmitting messages via UDP. /// </summary> public void StartTransmitting(string requestor) { logger.Info("[" + _description + "-M] Starting [req: " + requestor + "]"); _evtRaiser.RaiseEvent("StatusChangeRequest", "start", Niawa.Utilities.InlineSortedListCreator.CreateStrStr("str:Requestor", requestor), _threadStatus.NodeID, _threadStatus.ParentNodeID); //start client _stopped = false; //attempt lock bool tryLock = lockSection.WaitOne(60000); if (!tryLock) throw new TimeoutException("[" + _description + "-M] Could not obtain lock while starting [req: " + requestor + "]"); try { if (_threadStatus.IsThreadEnabled) { logger.Warn("[" + _description + "-M] Could not start: Transmit thread was already active [req: " + requestor + "]"); } else { /*v1*/ //System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, _port); /*v2*/ //_netUdpClient = new System.Net.Sockets.UdpClient(); //_netUdpClient.ExclusiveAddressUse = false; //_netUdpClient.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReuseAddress, true); //_netUdpClient.Client.Bind(_localEP); /*v3*/ _netUdpClient = new System.Net.Sockets.UdpClient(); _netUdpClient.ExclusiveAddressUse = false; _netUdpClient.Connect(_groupEndpoint); //start thread t1 = new System.Threading.Thread(TransmitThreadImpl); _sendQueue.Clear(); _threadStatus.IsThreadEnabled = true; //start UDP client t1.Start(); string logDetail = "[" + _description + "-M] Started [req: " + requestor + "]"; logger.Info(logDetail); //thread status _threadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_STARTED; } } catch (Exception ex) { logger.Error("[" + _description + "-M] Error during start transmitting: " + ex.Message, ex); throw ex; } finally { //release lock lockSection.Release(); } }
/// <summary> /// Resume transmitting messages via UDP. /// </summary> public void ResumeTransmitting(string requestor) { logger.Info("[" + _description + "-M] Resuming [req: " + requestor + "]"); _evtRaiser.RaiseEvent("StatusChangeRequest", "resume", Niawa.Utilities.InlineSortedListCreator.CreateStrStr("str:Requestor", requestor), _threadStatus.NodeID, _threadStatus.ParentNodeID); //resume client //attempt lock bool tryLock = lockSection.WaitOne(60000); if (!tryLock) throw new TimeoutException("[" + _description + "-M] Could not obtain lock while resuming [req: " + requestor + "]"); try { if (!_threadSuspended) { logger.Warn("[" + _description + "-M] Could not resume: transmit thread was not suspended [req: " + requestor + "]"); } else if (!_threadStatus.IsThreadEnabled) { logger.Warn("[" + _description + "-M] Could not resume: transmit thread was not active"); } else { if (_netUdpClient != null) _netUdpClient.Close(); _netUdpClient = null; //_groupEndpoint = null; //initialize UDP client /*v1*/ //_netUdpClient = new System.Net.Sockets.UdpClient(_port, System.Net.Sockets.AddressFamily.InterNetwork); //_groupEndpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, _port); /*v2*/ //_netUdpClient = new System.Net.Sockets.UdpClient(); //_netUdpClient.ExclusiveAddressUse = false; //_netUdpClient.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReuseAddress, true); //_netUdpClient.Client.Bind(_localEP); /*v3*/ _netUdpClient = new System.Net.Sockets.UdpClient(); _netUdpClient.ExclusiveAddressUse = false; _netUdpClient.Connect(_groupEndpoint); _threadSuspended = false; string logDetail = "[" + _description + "-M] Resumed [req: " + requestor + "]"; logger.Info(logDetail); //thread status _threadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_STARTED; } } catch (Exception ex) { logger.Error("[" + _description + "-M] Error during resume transmitting: " + ex.Message, ex); throw ex; } finally { //release lock lockSection.Release(); } }
public bool Start() { if (cbStarting != null) { cbStarting(null); } try { udp = new System.Net.Sockets.UdpClient(); udp.Connect(Host, UDPPort); Message("UDP connected"); } catch { Error("Failed to connect"); udp = null; if (cbStopped != null) { KeepRunning = cbStopped(null); } return(false); } try { com = new System.IO.Ports.SerialPort(); com.BaudRate = 4800; com.Parity = System.IO.Ports.Parity.None; com.StopBits = System.IO.Ports.StopBits.One; com.DataBits = 8; com.ReadBufferSize = 4096; com.ReadTimeout = 1500; com.PortName = ComPort; com.Open(); Message("COM open"); } catch { Error("Failed to open com"); udp = null; com = null; if (cbStopped != null) { cbStopped(null); } return(false); } if (cbStarted != null) { cbStarted(""); } KeepRunning = true; return(true); }
// 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()
unsafe private void btnSend_Click(object sender, EventArgs e) { int inv_ms = Convert.ToInt32(txtInv.Text); byte[] byt; int n = 0; byte[] fbyt = new byte[1518]; if (chkUseWS.Checked) { IPAddress ipa = ((CbxObjectItem)cbxNic.SelectedItem).ipv4.Addr.ipAddress; Array.Resize(ref fbyt, 65535 - (IP_HDR_SIZE + UDP_HDR_SIZE)); //UdpClientオブジェクトを作成する System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient( new IPEndPoint(ipa, Convert.ToInt16(txtPortL.Text))); int calc_sec = Convert.ToInt32(txtInv.Text); int mbps_conv = (cbxUnit.SelectedIndex == 0) ? MBPS_CONV1 : MBPS_CONV2; ulong rw_old; total_cnt = rw_cnt = rw_old = 0; rw_bytes = new ulong[calc_sec + 3]; /* 初回と最後尾のバッファは作業用 */ tmMain = new System.Timers.Timer(); tmMain.Elapsed += new ElapsedEventHandler(tmMain_Elapsed); tmMain.Interval = 1000; TaskFactory tf = new TaskFactory(); CancellationTokenSource cts = new CancellationTokenSource(); long dstip = IPAddress.Parse(txtIPaR.Text).Address; udp.Connect(new IPAddress(dstip), Convert.ToInt32(txtPortR.Text)); /* ARPキャッシュに静的に登録されてなければ登録する */ int arp_ret = arp_check((int)dstip); if (arp_ret != (int)MIB_IPNET_TYPE.STATIC) { byt = str2hexs(txtMacR.Text, '-'); arp_update((int)dstip, byt, (int)MIB_IPNET_TYPE.STATIC); } Task tsk = tf.StartNew(() => { for (; ;) { rw_bytes[rw_cnt] += (ulong)udp.Send(fbyt, fbyt.Length); cts.Token.ThrowIfCancellationRequested(); /* キャンセル発行確認 */ } }, cts.Token); txtResS.Clear(); /* 初回の測定値は捨てる */ tmMain.Start(); while (rw_cnt == rw_old) { System.Threading.Thread.Sleep(100); System.Windows.Forms.Application.DoEvents(); } /* 2回目以降から測定を開始 (配列の最後尾1つ手前で終了) */ rw_old = rw_cnt; do { if (rw_cnt != rw_old) { rw_old = rw_cnt; txtResS.AppendText(string.Format("{0:f3} Mbps/sec" + Environment.NewLine, rw_bytes[rw_old - 1] / (double)mbps_conv)); txtResS.Refresh(); } System.Threading.Thread.Sleep(100); System.Windows.Forms.Application.DoEvents(); } while (rw_cnt <= (ulong)calc_sec + 1); tmMain.Stop(); try { cts.Cancel(); /* 送信終了 */ } catch (AggregateException) { } finally { //UdpClientを閉じる udp.Close(); /* arpキャッシュから削除する */ //if (arp_ret != (int)MIB_IPNET_TYPE.STATIC) { byt = str2hexs(txtMacR.Text, '-'); arp_delete((int)dstip, byt, (int)MIB_IPNET_TYPE.STATIC); } } } else { short framesize = Convert.ToInt16(txtFrasize.Text); /*---- Ethernet ヘッダー ---------------------------------*/ /* ローカルMACアドレス */ byt = str2hexs(txtMacR.Text, '-'); Array.Copy(byt, 0, fbyt, n, MAC_ADDR_SIZE); n += MAC_ADDR_SIZE; /* リモートMACアドレス */ byt = str2hexs(txtMacL.Text, '-'); Array.Copy(byt, 0, fbyt, n, MAC_ADDR_SIZE); n += MAC_ADDR_SIZE; fbyt[n++] = 0x08; fbyt[n++] = 0x00; /*---- IP ヘッダー ---------------------------------------*/ fbyt[n++] = 0x45; fbyt[n++] = 0x00; fixed(byte *wk = &fbyt[n]) /* Length */ { framesize -= ETH_HDR_SIZE; *(short *)wk = IPAddress.HostToNetworkOrder((short)framesize); } n += sizeof(short); fixed(byte *wk = &fbyt[n]) /* Identification */ { *(short *)wk = IPAddress.HostToNetworkOrder((short)1); } n += sizeof(short); fbyt[n++] = 0x00; /* Flags */ fbyt[n++] = 0x00; /* Fragment offset */ fbyt[n++] = 0x40; /* TTL */ fbyt[n++] = 0x11; /* Protocol (UDP) */ fbyt[n++] = 0x00; /* IP checksum */ fbyt[n++] = 0x00; /* ローカルIPアドレス */ byt = str2hexs(txtIPaL.Text, '.', true); Array.Copy(byt, 0, fbyt, n, IP_ADDR_SIZE); n += IP_ADDR_SIZE; /* リモートIPアドレス */ byt = str2hexs(txtIPaR.Text, '.', true); Array.Copy(byt, 0, fbyt, n, IP_ADDR_SIZE); n += IP_ADDR_SIZE; /*---- UDP ヘッダー --------------------------------------*/ fixed(byte *wk = &fbyt[n]) /* Source Port */ { *(short *)wk = IPAddress.HostToNetworkOrder((short)Convert.ToUInt16(txtPortL.Text)); } n += sizeof(short); fixed(byte *wk = &fbyt[n]) /* Destination Port */ { *(short *)wk = IPAddress.HostToNetworkOrder((short)Convert.ToUInt16(txtPortR.Text)); } n += sizeof(short); fixed(byte *wk = &fbyt[n]) /* Length */ { framesize -= IP_HDR_SIZE; *(short *)wk = IPAddress.HostToNetworkOrder((short)framesize); } n += sizeof(short); fbyt[n++] = 0x00; /* UDP checksum */ fbyt[n++] = 0x00; /* Payload */ framesize -= UDP_HDR_SIZE; n += framesize; Array.Resize(ref fbyt, n); /* Update checksum */ update_ip_csum(fbyt); update_udp_csum(fbyt); if (cbxCalc.SelectedIndex == 1) { /* Payload */ n -= CALC_DIFF_SIZE2; /* ヘッダ分を引く */ } /*--------------------------------------------------------*/ int calc_sec = Convert.ToInt32(txtInv.Text); int mbps_conv = (cbxUnit.SelectedIndex == 0) ? MBPS_CONV1 : MBPS_CONV2; ulong rw_old; total_cnt = rw_cnt = rw_old = 0; rw_bytes = new ulong[calc_sec + 3]; /* 初回と最後尾のバッファは作業用 */ tmMain = new System.Timers.Timer(); tmMain.Elapsed += new ElapsedEventHandler(tmMain_Elapsed); tmMain.Interval = 1000; TaskFactory tf = new TaskFactory(); CancellationTokenSource cts = new CancellationTokenSource(); Debug.WriteLine("SelectedIndex : " + cbxNic.SelectedIndex); /* SharpPcapデバイスオープン */ LibPcapLiveDevice dev = LibPcapLiveDeviceList.Instance[cbxNic.SelectedIndex]; dev.Open(); Task tsk = tf.StartNew(() => { for (; ;) { dev.SendPacket(fbyt, fbyt.Length); rw_bytes[rw_cnt] += (ulong)n; cts.Token.ThrowIfCancellationRequested(); /* キャンセル発行確認 */ } }, cts.Token); txtResS.Clear(); /* 初回の測定値は捨てる */ tmMain.Start(); while (rw_cnt == rw_old) { System.Threading.Thread.Sleep(100); System.Windows.Forms.Application.DoEvents(); } /* 2回目以降から測定を開始 (配列の最後尾1つ手前で終了) */ rw_old = rw_cnt; do { if (rw_cnt != rw_old) { rw_old = rw_cnt; txtResS.AppendText(string.Format("{0:f3} Mbps/sec" + Environment.NewLine, rw_bytes[rw_old - 1] / (double)mbps_conv)); txtResS.Refresh(); } System.Threading.Thread.Sleep(100); System.Windows.Forms.Application.DoEvents(); } while (rw_cnt <= (ulong)calc_sec + 1); tmMain.Stop(); try { cts.Cancel(); /* 送信終了 */ } catch (AggregateException) { } finally { dev.Close(); } } #if true #else ///* SharpPcapデバイスオープン */ //Debug.WriteLine("SelectedIndex : " + cbxNic.SelectedIndex); //LibPcapLiveDevice dev = LibPcapLiveDeviceList.Instance[cbxNic.SelectedIndex]; //dev.Open(); //dev.NonBlockingMode = true; //for (int x = 0; x < inv_ms; x++) //{ // dev.SendPacket(fbyt, fbyt.Length); //} //dev.Close(); Array.Resize(ref fbyt, 65500); //UdpClientオブジェクトを作成する System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient(new IPEndPoint(IPAddress.Parse("172.16.0.100"), 60000)); udp.Connect(IPAddress.Parse(txtIPaR.Text), Convert.ToInt32(txtPortR.Text)); for (int x = 0; x < inv_ms; x++) { udp.Send(fbyt, fbyt.Length); } //UdpClientを閉じる udp.Close(); #endif }
public UdpClient() { server.Connect(Program.ServerIP, 16000); }