/// <summary> /// Class constructor. Instantiates a new <see cref="TXIPv4Packet"/> object with the given /// parameters. /// </summary> /// <param name="frameID">Frame ID.</param> /// <param name="destAddress">32-bit IP address of the destination device.</param> /// <param name="destPort">Destination port number.</param> /// <param name="sourcePort">Source port number.</param> /// <param name="protocol">Protocol used for transmitted data.</param> /// <param name="transmitOptions">Transmit options bitfield.</param> /// <param name="data">Transmit data bytes.</param> /// <exception cref="ArgumentException">If <c><paramref name="frameID"/> <![CDATA[<]]> 0 </c> /// or if <c><paramref name="frameID"/> <![CDATA[>]]> 255 </c> /// or if <c><paramref name="destPort"/> <![CDATA[<]]> 0</c> /// or if <c><paramref name="destPort"/> <![CDATA[>]]> 65535</c> /// or if <c><paramref name="sourcePort"/> <![CDATA[<]]> 0</c> /// or if <c><paramref name="sourcePort"/> <![CDATA[>]]> 65535</c> /// or if <paramref name="transmitOptions"/> is invalid /// or if <paramref name="protocol"/> is unknown.</exception> /// <seealso cref="IPAddress"/> /// <seealso cref="IPProtocol"/> /// <see cref="IPAddress"/> /// <see cref="IPProtocol"/> public TXIPv4Packet(byte frameID, IPAddress destAddress, int destPort, int sourcePort, IPProtocol protocol, int transmitOptions, byte[] data) : base(APIFrameType.TX_IPV4) { if (destPort < 0 || destPort > 65535) { throw new ArgumentException(ERROR_PORT_ILLEGAL); } if (sourcePort < 0 || sourcePort > 65535) { throw new ArgumentException(ERROR_PORT_ILLEGAL); } if (transmitOptions != OPTIONS_CLOSE_SOCKET && transmitOptions != OPTIONS_LEAVE_SOCKET_OPEN) { throw new ArgumentException(ERROR_OPTIONS_INVALID); } if (protocol == IPProtocol.UNKNOWN) { throw new ArgumentNullException(ERROR_PROTOCOL_UNKNOWN); } FrameID = frameID; this.destAddress = destAddress ?? throw new ArgumentNullException(ERROR_DEST_ADDR_NULL); this.destPort = destPort; this.sourcePort = sourcePort; this.protocol = protocol; this.transmitOptions = transmitOptions; Data = data; logger = LogManager.GetLogger <TXIPv4Packet>(); }
/// <summary> /// Creates a new instance of this class /// </summary> /// <param name="ipaRemoteBinding">The remote address to bind this socket to</param> /// <param name="ipaLocalBinding">The local address to bind this socket to</param> /// <param name="ipPotocol">The protocl this socket belongs to</param> public IPSocket(IPAddress ipaRemoteBinding, IPAddress ipaLocalBinding, IPProtocol ipPotocol) { if (ipaRemoteBinding.AddressFamily != ipaLocalBinding.AddressFamily) { throw new ArgumentException("It is not possible to mix up addresses of different types."); } if (ipaRemoteBinding.AddressFamily == AddressFamily.InterNetworkV6) { iIPVersion = 6; } else if (ipaRemoteBinding.AddressFamily == AddressFamily.InterNetwork) { iIPVersion = 4; } else { throw new ArgumentException("Only IPv4 and IPv6 addresses are supported at the moment."); } rRandom = new Random(); LocalBinding = ipaLocalBinding; ProtocolBinding = ipPotocol; RemoteBinding = ipaRemoteBinding; MaximumTransmissionUnit = 1500; dictIDFragmentBuffer = new Dictionary <uint, MemoryStream>(); }
public IPAddress GetHostAddressForType(string hostNameOrAddress, IPProtocol protocol) { IPAddress tempAddress = IPProtocol.IPv4 == protocol ? IPAddress.Any : IPAddress.IPv6Any; try { IPHostEntry entry = ipNetworkFactory.GetHostEntry(hostNameOrAddress); AddressFamily addressFamily = IPProtocol.IPv4 == protocol ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6; foreach (IPAddress address in entry.AddressList) { if (addressFamily == address.AddressFamily) { return(address); } } } catch (Exception ex) { String message = String.Format("GetHostAddressForType cannot DNS host \"{0}\" {1}", hostNameOrAddress, ex); logManager.LogDebugError(message); } return(tempAddress); }
/// <summary> /// Starts port listeners and sends a request to the PortMapSleuth server for testing. /// </summary> /// <param name="ipProtocol"></param> /// <param name="ports"></param> /// <returns>Returns successful if all ports succeeded.</returns> public void TestPorts(IPProtocol ipProtocol, List <int> ports) { var portMapRequest = new PortTestRequest { Ports = ports, IPProtocol = ipProtocol }; string portMapRequestJSON = JsonConvert.SerializeObject(portMapRequest); UdpClientListeners = new List <UdpClient>(); try { // Create the udp listeners: foreach (var port in ports) { UdpClientListeners.Add(StartUDPListener(port)); } // Send out the port test request: StartWebRequest(portMapRequestJSON); } catch (Exception e) { // Error codes: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx Console.WriteLine(e.ToString()); PortTestException(); } }
// https://stackoverflow.com/a/50706466/2374053 private static string GetLocalAddress(IPProtocol ipProtocol = IPProtocol.IPv4) { var firstAddress = (from address in NetworkInterface.GetAllNetworkInterfaces().Select(x => x.GetIPProperties()).SelectMany(x => x.UnicastAddresses).Select(x => x.Address) where !IPAddress.IsLoopback(address) && address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork select address).FirstOrDefault(); return((ipProtocol == IPProtocol.IPv4) ? firstAddress?.MapToIPv4().ToString() : firstAddress?.MapToIPv6().ToString()); }
private unsafe byte[] ConstructIP4Packet( byte ipversion, ushort id, byte flags, ushort fragmentoffset, IPProtocol protocol, uint source_address, uint destination_address, byte[] data, bool bHardware = false ) { int size = sizeof(IPv4Header) + (data?.Length ?? 0); byte[] ret = new byte[size]; IPv4Header header = new IPv4Header(); header.version_ihl = (byte)((ipversion << 4) + (sizeof(IPv4Header) / 4)); header.tos_ecn = 0; if (!bHardware) { header.packet_length = Utility.htons((ushort)ret.Length); } header.identification = Utility.htons(id); //header.flags_fragmentoffset = (ushort)(flags + Utility.htons((ushort)(fragmentoffset << 3))); header.flags_fragmentoffset = (ushort)((flags << 4) + (Utility.htons(fragmentoffset) >> 3)); header.ttl = 0; header.protocol = protocol; header.checksum = 0; header.ip_srcaddr = source_address; // not sure why, these are not coming across the wire as net order? header.ip_destaddr = destination_address; // not sure why, these are not coming across the wire as net order? IntPtr ptr = IntPtr.Zero; try { ptr = Marshal.AllocHGlobal(sizeof(IPv4Header)); Marshal.StructureToPtr(header, ptr, true); Marshal.Copy(ptr, ret, 0, sizeof(IPv4Header)); } finally { if (ptr != IntPtr.Zero) { Marshal.FreeHGlobal(ptr); } } if ((data?.Length ?? 0) > 0) { Array.Copy(data, 0, ret, sizeof(IPv4Header), data.Length); } return(ret); }
/// <summary> /// Gets the IP protocol for the given ID. /// </summary> /// <param name="source"></param> /// <param name="id">ID value to retrieve <see cref="IPProtocol"/>.</param> /// <returns>The IP protocol for the given ID., <see cref="IPProtocol.UNKNOWN"/> /// if the <paramref name="id"/> could not be found in the list.</returns> public static IPProtocol Get(this IPProtocol source, int id) { var values = Enum.GetValues(typeof(IPProtocol)); if (values.OfType <int>().Contains(id)) { return((IPProtocol)id); } return(IPProtocol.UNKNOWN); }
/// <summary> /// Creates a new instance of this class /// </summary> public IPv4Frame() { this.iVersion = 4; this.tosTypeOfService = new IPTypeOfService(); this.iIdentification = 0; this.ifFlags = new IPFlags(false, false); this.iFragmentOffset = 0; this.iTimeToLive = 0xFF; this.iProtocol = IPProtocol.Other; this.ipaSource = IPAddress.Any; this.ipaDestination = IPAddress.Any; this.ipoOptions = new IPv4Options(); }
internal static void UpdateIPv4Node(TreeView treeView, IPv4Packet ipv4Packet) { TreeNode ipv4Node = treeView.Nodes["IPv4"]; if (ipv4Node == null) { ipv4Node = AddIPv4Node(treeView); } ipv4Node.Text = String.Format("Internet Protocol V4 (IPv4), Src: {0}, Dst: {1}", ipv4Packet.SourceAddress, ipv4Packet.DestinationAddress); ipv4Node.Nodes["Version"].Text = String.Format("Version: {0}", ipv4Packet.Version); ipv4Node.Nodes["IHL"].Text = String.Format("Header length: {0} bytes", ipv4Packet.IPHeaderLength); TreeNode dsNode = ipv4Node.Nodes["DS"]; dsNode.Text = String.Format("Differentiated Services field: 0x{0:X2}", ipv4Packet.TypeOfService); dsNode.Nodes["Precedence"].Text = GetIPv4PrecedenceText(ipv4Packet.Precedence); bool minimizeDelay = ipv4Packet.MinimizeDelay; dsNode.Nodes["Delay"].Text = String.Format(". . . {0} . . . . = Delay: {1}", minimizeDelay ? "1" : "0", minimizeDelay ? "Low" : "Normal"); bool maximizeThroughput = ipv4Packet.MaximizeThroughput; dsNode.Nodes["Throughput"].Text = String.Format(". . . . {0} . . . = Throughput: {1}", maximizeThroughput ? "1" : "0", maximizeThroughput ? "High" : "Normal"); bool maximizeReliability = ipv4Packet.MaximizeReliability; dsNode.Nodes["Reliability"].Text = String.Format(". . . . . {0} . . = Reliability: {1}", maximizeReliability ? "1" : "0", maximizeReliability ? "High" : "Normal"); bool minimizeCost = ipv4Packet.MinimizeMonetaryCost; dsNode.Nodes["Cost"].Text = String.Format(". . . . . . {0} . = Cost: {1}", minimizeCost ? "1" : "0", minimizeCost ? "Minimize Monetary Cost" : "Normal"); ipv4Node.Nodes["TotalLength"].Text = String.Format("Total length: {0} bytes", ipv4Packet.IPTotalLength); ipv4Node.Nodes["Id"].Text = String.Format("Identification: 0x{0:X4} ({0})", ipv4Packet.Id); TreeNode flagsNode = ipv4Node.Nodes["Flags"]; flagsNode.Text = String.Format("Flags: 0x{0:X2}", ipv4Packet.FragmentFlags); flagsNode.Nodes["Reserved"].Text = String.Format("{0} . . = Reserved bit: {1}", ipv4Packet.ReservedFlag ? "1" : "0", ipv4Packet.ReservedFlag ? "Set" : "Not set"); flagsNode.Nodes["DF"].Text = String.Format(". {0} . = Don't fragment: {1}", ipv4Packet.DontFragment ? "1" : "0", ipv4Packet.DontFragment ? "Set" : "Not set"); flagsNode.Nodes["MF"].Text = String.Format(". . {0} = More fragments: {1}", ipv4Packet.MoreFragments ? "1" : "0", ipv4Packet.MoreFragments ? "Set" : "Not set"); ipv4Node.Nodes["FragmentOffset"].Text = String.Format("Fragment offset: {0}", ipv4Packet.FragmentOffset); ipv4Node.Nodes["TTL"].Text = String.Format("Time to live: {0}", ipv4Packet.TimeToLive); ipv4Node.Nodes["Protocol"].Text = String.Format("Protocol: {0}", IPProtocol.getDescription(ipv4Packet.IPProtocol)); ipv4Node.Nodes["Checksum"].Text = String.Format("Header checksum: 0x{0:X4} ({1})", ipv4Packet.IPChecksum, ipv4Packet.ValidIPChecksum ? "correct" : "incorrect"); ipv4Node.Nodes["SA"].Text = String.Format("Source address: {0}", ipv4Packet.SourceAddress); ipv4Node.Nodes["DA"].Text = String.Format("Destination address: {0}", ipv4Packet.DestinationAddress); }
/// <summary> /// Class constructor. Instantiates a new object of type <see cref="IPMessage"/> with the /// given parameters. /// </summary> /// <param name="ipAddress">The IP address the message comes from.</param> /// <param name="sourcePort">TCP or UDP source port of the transmission.</param> /// <param name="destPort">TCP or UDP destination port of the transmission.</param> /// <param name="protocol">IP protocol used in the transmission.</param> /// <param name="data">Byte array containing the data of the message.</param> /// <exception cref="ArgumentNullException">If <paramref name="ipAddress"/> is <c>null</c> /// or if <paramref name="data"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException">If <paramref name="sourcePort"/> is <c>null</c> or invalid, /// or if <paramref name="destPort"/> is <c>null</c> or invalid, /// or if <paramref name="protocol"/> is <see cref="IPProtocol.UNKNOWN"/>.</exception> public IPMessage(IPAddress ipAddress, int sourcePort, int destPort, IPProtocol protocol, byte[] data) { if (protocol == IPProtocol.UNKNOWN) { throw new ArgumentException("Protocol cannot be unknown."); } if (sourcePort < 0 || sourcePort > 65535) { throw new ArgumentException("Source port must be between 0 and 65535."); } if (destPort < 0 || destPort > 65535) { throw new ArgumentException("Destination port must be between 0 and 65535."); } IPAddress = ipAddress ?? throw new ArgumentNullException("IP address cannot be null."); SourcePort = sourcePort; DestPort = destPort; Protocol = protocol; Data = data ?? throw new ArgumentNullException("Data cannot be null."); }
/// <summary> /// Class constructor. Instantiates a new <c>RXIPv4Packet</c> object with /// the given parameters. /// </summary> /// <param name="sourceAddress">32-bit IP address of the source device.</param> /// <param name="destPort">Destination port number.</param> /// <param name="sourcePort">Source port number.</param> /// <param name="protocol">Protocol used for transmitted data.</param> /// <param name="data">Receive data bytes.</param> /// <exception cref="ArgumentException">If <c><paramref name="destPort"/> <![CDATA[<]]> 0</c> /// or if <c><paramref name="destPort"/> <![CDATA[>]]> 65535</c> /// or if <c><paramref name="sourcePort"/> <![CDATA[<]]> 0</c> /// or if <c><paramref name="sourcePort"/> <![CDATA[>]]> 65535</c> /// or if <paramref name="protocol"/> is unknown.</exception> /// <seealso cref="IPAddress"/> /// <seealso cref="IPProtocol"/> public RXIPv4Packet(IPAddress sourceAddress, int destPort, int sourcePort, IPProtocol protocol, byte[] data) : base(APIFrameType.RX_IPV4) { if (destPort < 0 || destPort > 65535) { throw new ArgumentException(ERROR_PORT_ILLEGAL); } if (sourcePort < 0 || sourcePort > 65535) { throw new ArgumentException(ERROR_PORT_ILLEGAL); } if (protocol == IPProtocol.UNKNOWN) { throw new ArgumentException(ERROR_PROTOCOL_UNKNOWN); } this.sourceAddress = sourceAddress ?? throw new ArgumentNullException(ERROR_SOURCE_ADDR_NULL); this.destPort = destPort; this.sourcePort = sourcePort; this.protocol = protocol; Data = data; logger = LogManager.GetLogger <RXIPv4Packet>(); }
public IPHeader(EthernetHeader eth) { if (eth.Protocol == (int)EthernetProtocol.IP) { headerOffset = eth.DataOffset; data = eth.Data; long addr = (long)data[headerOffset + 15] << 24 | (long)data[headerOffset + 14] << 16 | (long)data[headerOffset + 13] << 8 | (long)data[headerOffset + 12]; sourceIp = new IPAddress(addr); addr = (long)data[headerOffset + 19] << 24 | (long)data[headerOffset + 18] << 16 | (long)data[headerOffset + 17] << 8 | (long)data[headerOffset + 16]; destinationIp = new IPAddress(addr); protocol = (IPProtocol)data[headerOffset + 9]; length = data[headerOffset + 2] << 8 | data[headerOffset + 3]; dataOffset = headerOffset + ((data[headerOffset] & 0xF) << 2); } else { throw new PacketFormatException("Packet is not IP"); } }
/// <summary> /// Gets the IP protocol name. /// </summary> /// <param name="source"></param> /// <returns>The IP protocol name.</returns> public static string GetName(this IPProtocol source) { return(lookupTable[source]); }
/// <summary> /// Gets the IP protocol ID. /// </summary> /// <param name="source"></param> /// <returns>The IP protocol ID.</returns> public static int GetID(this IPProtocol source) { return((int)source); }
/// <summary> /// class constructor /// </summary> /// <param name="sourceIP">Source IP address to filter packets, in host byte order</param> /// <param name="destinationIP">Destination IP address to filter packets, in host byte order</param> /// <param name="protocol">Layer-4 Protocol ID to filter packets</param> public IPDecoder(uint sourceIP, uint destinationIP, IPProtocol protocol) { _sourceIP = sourceIP; _destinationIP = destinationIP; _protocol = protocol; }
// Use this for initialization private void Start() { //try //{ string destPlatform = String.Empty; #if UNITY_ANDROID destPlatform = "Android"; #endif #if UNITY_IPHONE destPlatform = "iOS"; #endif string fileNameWithPath = String.Format("TextFiles/{0}.txt", destPlatform); // Get data from Resources. IResourceManager resourceManager = new ResourceManager(); TextAsset asset = (TextAsset)resourceManager.LoadResourceImmediate(typeof(TextAsset), fileNameWithPath); String text = asset.text; string host = resourceManager.GetInformationFromFile(text, "HOST"); port = Convert.ToInt32(resourceManager.GetInformationFromFile(text, "PORT")); // Get data from Streaming Assets string fileRoot = Application.streamingAssetsPath; string fullPath = fileRoot + "/GameServer.txt"; IConfigManager configManager = new ConfigManager(); host = configManager.GetInformationFromFile(fullPath, host); // Invoke IP Manger for IP Protocol ILogManager logManager = new LogManager(); logManager.Initialize(TargetEnvironment.Test); IIPNetworkFactory ipNetworkFactory = new IPNetworkFactory(); IPNetworkManager ipNetworkManager = new IPNetworkManager(ipNetworkFactory, logManager); IPProtocol ipProtocol = ipNetworkManager.GetNetworkProtocolsFromDNS(host); IPAddress netIPAddress = IPProtocol.IPv4 == ipProtocol ? IPAddress.Any : IPAddress.IPv6Any; AddressFamily netAddressFamily = IPProtocol.IPv4 == ipProtocol ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6; NetGameConfiguration netGameConfiguration = new NetGameConfiguration(netIPAddress, netAddressFamily); // Convert IP address IPAddress ipAddress = ipNetworkManager.GetHostAddressForType(host, ipProtocol); hostip = ipAddress.ToString(); // Create new instance of configs. Parameter is "application Id". It has to be same on client and server. NetPeerConfiguration Config = new NetPeerConfiguration("game", netGameConfiguration); // Create new client, with previously created configs Client = new NetClient(Config, netGameConfiguration); // Create new outgoing message NetOutgoingMessage outmsg = Client.CreateMessage(); //LoginPacket lp = new LoginPacket("Katu"); // Start client Client.Start(); // Write byte ( first byte informs server about the message type ) ( This way we know, what kind of variables to read ) outmsg.Write((byte)PacketTypes.LOGIN); // Write String "Name" . Not used, but just showing how to do it outmsg.Write("MyName"); // Connect client, to ip previously requested from user Client.Connect(hostip, port, outmsg); ResultText = "Client Started"; // Create the list of characters GameStateList = new List <Character>(); // Funtion that waits for connection approval info from server WaitForStartingInfo(); //} //catch (Exception ex) //{ // ErrorText = ex.ToString(); //} }
/// <summary> /// Creates a new instance of this class /// </summary> /// <param name="localBinding">The local binding information</param> /// <param name="remoteBinding">The remote binding Information</param> /// <param name="protocolBinding">The protocol binding Information</param> public IPBindingInformation(IPEndPoint localBinding, IPEndPoint remoteBinding, IPProtocol protocolBinding) : base(localBinding, remoteBinding) { ProtocolBinding = protocolBinding; }
public void Assign(IPHeader ip, UdpHeader udp) { Source = new IPEndPoint(ip.SourceIp, udp.SourcePort); Destination = new IPEndPoint(ip.DestinationIp, udp.DestinationPort); Protocol = ip.Protocol; }
/// <summary> /// Creates a new instance of this class by parsing the given data. /// </summary> /// <param name="bRaw">The data to parse</param> public IPv4Frame(byte[] bRaw) { int iHeaderLength; int iTotalLength; if (bRaw.Length < 20) { throw new ArgumentException("Invalid packet"); } this.iVersion = (bRaw[0] & 0xF0) >> 4; iHeaderLength = (bRaw[0] & 0x0F) * 4; this.iHeaderLength = iHeaderLength; if (iHeaderLength < 20) { throw new ArgumentException("Invalid packet header"); } this.tosTypeOfService = new IPTypeOfService(bRaw[1]); iTotalLength = (int)bRaw[2] * 256 + (int)bRaw[3]; if (iTotalLength > bRaw.Length) { throw new ArgumentException("Corrupt packet length"); } this.iIdentification = bRaw[4] * (uint)256 + bRaw[5]; this.ifFlags = new IPFlags((bRaw[6] & 0x40) != 0, ((bRaw[6] & 0x20)) != 0); this.iFragmentOffset = 0; this.iFragmentOffset |= (byte)((bRaw[6] & 0x1F) << 8); this.iFragmentOffset |= (byte)(bRaw[7]); this.iTimeToLive = bRaw[8]; if (Enum.IsDefined(typeof(IPProtocol), (int)bRaw[9])) { this.iProtocol = (IPProtocol)bRaw[9]; } else { this.iProtocol = IPProtocol.Other; } ipaSource = new IPAddress(BitConverter.ToUInt32(bRaw, 12)); ipaDestination = new IPAddress(BitConverter.ToUInt32(bRaw, 16)); if (iHeaderLength > 20) { byte[] bOptionData = new byte[iHeaderLength - 20]; for (int iC1 = 20; iC1 < iHeaderLength - 20; iC1++) { bOptionData[iC1] = bRaw[iC1 + 20]; } this.ipoOptions = new IPv4Options(bOptionData); } else { this.ipoOptions = new IPv4Options(); } Encapsulate(bRaw, iHeaderLength, iTotalLength - iHeaderLength); }
/// <summary> /// Returns the <see cref="IPProtocol"/> in string format. /// </summary> /// <param name="source"></param> /// <returns>The <see cref="IPProtocol"/> in string format.</returns> public static string ToDisplayString(this IPProtocol source) { return(lookupTable[source]); }
static void Main() { // Ask for IP // Read Ip to string string host = ConfigurationManager.AppSettings["host"]; port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]); ILogManager logManager = new LogManager(); logManager.Initialize(TargetEnvironment.Test); IIPNetworkFactory ipNetworkFactory = new IPNetworkFactory(); IPNetworkManager ipNetworkManager = new IPNetworkManager(ipNetworkFactory, logManager); IPProtocol ipProtocol = ipNetworkManager.GetNetworkProtocolsFromDNS(host); IPAddress netIPAddress = IPProtocol.IPv4 == ipProtocol ? IPAddress.Any : IPAddress.IPv6Any; AddressFamily netAddressFamily = IPProtocol.IPv4 == ipProtocol ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6; NetGameConfiguration netGameConfiguration = new NetGameConfiguration(netIPAddress, netAddressFamily); // Convert IP address IPAddress ipAddress = ipNetworkManager.GetHostAddressForType(host, ipProtocol); hostip = ipAddress.ToString(); Console.WriteLine("Enter IP To Connect - {0}:{1}", hostip, port); Console.Read(); // Create new instance of configs. Parameter is "application Id". It has to be same on client and server. NetPeerConfiguration Config = new NetPeerConfiguration("game", netGameConfiguration); // Create new client, with previously created configs Client = new NetClient(Config, netGameConfiguration); // Create new outgoing message NetOutgoingMessage outmsg = Client.CreateMessage(); //LoginPacket lp = new LoginPacket("Katu"); // Start client Client.Start(); // Write byte ( first byte informs server about the message type ) ( This way we know, what kind of variables to read ) outmsg.Write((byte)PacketTypes.LOGIN); // Write String "Name" . Not used, but just showing how to do it outmsg.Write("MyName"); // Connect client, to ip previously requested from user Client.Connect(hostip, port, outmsg); Console.WriteLine("Client Started"); // Create the list of characters GameStateList = new List <Character>(); // Set timer to tick every 50ms update = new System.Timers.Timer(50); // When time has elapsed ( 50ms in this case ), call "update_Elapsed" funtion update.Elapsed += new System.Timers.ElapsedEventHandler(update_Elapsed); // Funtion that waits for connection approval info from server WaitForStartingInfo(); // Start the timer update.Start(); // While..running while (IsRunning) { // Just loop this like madman GetInputAndSendItToServer(); } }
public static void Test() { Byte[] buffer = new Byte[4096]; //Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); //sock.Bind(new IPEndPoint(IPAddress.Any, 0)); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); sock.Bind(new IPEndPoint(IPAddress.Any, 0)); //sock.Bind(new IPEndPoint(IPAddress.Parse("15.8.29.69"), 0)); sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1); //byte[] trueBytes = new byte[] { 1, 0, 0, 0 }; //byte[] outBytes = new byte[] { 0, 0, 0, 0 }; //sock.IOControl(IOControlCode.ReceiveAll, trueBytes, outBytes); int i = 10; while (true) { if (i >= 10) { i = 0; Console.WriteLine("---------------------------------------------------------------------------"); Console.WriteLine("DateTime | Bytes | IP Source Destination | Data"); Console.WriteLine("---------------------------------------------------------------------------"); } //Console.WriteLine("Waiting for packet..."); int received = sock.Receive(buffer); if (received < 20) { if (received > 0) { Console.WriteLine("Error: packets must be at least 20 byte but found one that was {0}", received); } else { Console.WriteLine("Socket.Receive returned {0}", received); break; } } if (received > 0) { Byte ipHeaderLength = (Byte)((buffer[0] & 0xF) << 2); Byte protocol = buffer[9]; Byte[] srcAddress = new Byte[] { buffer[12], buffer[13], buffer[14], buffer[15] }; Byte[] dstAddress = new Byte[] { buffer[16], buffer[17], buffer[18], buffer[19] }; //Console.Write("{0,9} | {1,2} {2,15} {3,15} | ", received, // ipHeaderLength, new IPAddress(srcAddress), new IPAddress(dstAddress)); UInt16 srcPort, dstPort; switch (protocol) { case (Byte)IPProtocol.Tcp: srcPort = (UInt16)(buffer[ipHeaderLength] << 8 | buffer[ipHeaderLength + 1]); dstPort = (UInt16)(buffer[ipHeaderLength + 2] << 8 | buffer[ipHeaderLength + 3]); UInt32 sequenceNumber = (UInt32)( (buffer[ipHeaderLength + 4] << 24) | (0xFF0000 & (buffer[ipHeaderLength + 5] << 16)) | (0xFF00 & (buffer[ipHeaderLength + 6] << 8)) | (0xFF & (buffer[ipHeaderLength + 7]))); UInt32 acknowledgementNumber = (UInt32)( (buffer[ipHeaderLength + 8] << 24) | (0xFF0000 & (buffer[ipHeaderLength + 9] << 16)) | (0xFF00 & (buffer[ipHeaderLength + 10] << 8)) | (0xFF & (buffer[ipHeaderLength + 11]))); int tcpHeaderLength = (buffer[ipHeaderLength + 12] >> 4) << 2; Byte flags = buffer[13]; Boolean synFlag = (flags & 0x02) != 0; Boolean ackFlag = (flags & 0x10) != 0; Boolean pshFlag = (flags & 0x08) != 0; String flagsString = (synFlag ? (ackFlag ? (pshFlag ? "SYN-ACK-PSH" : "SYN-ACK") : (pshFlag ? "SYN-PSH" : "SYN")) : (ackFlag ? (pshFlag ? "ACK-PSH" : "ACK") : (pshFlag ? "PSH" : String.Empty))); i++; Console.Write("{0,-20} | {1,9} | {2,2} {3,15} {4,15} | ", DateTime.Now, received, ipHeaderLength, new IPAddress(srcAddress), new IPAddress(dstAddress)); int dataLength = received - ipHeaderLength - tcpHeaderLength; if (dataLength > 0) { Console.WriteLine("Tcp {0,5} > {1,-5} Seq=0x{2,-8:X} {3} DataLength={4}", srcPort, dstPort, sequenceNumber, ackFlag ? String.Format("Ack=0x{0,-8:X}", acknowledgementNumber) : String.Empty, dataLength); } else { Console.WriteLine("Tcp {0,5} > {1,-5} {2,11} Seq=0x{3,-8:X} {4}", srcPort, dstPort, flagsString, sequenceNumber, ackFlag ? String.Format("Ack=0x{0,-8:X}", acknowledgementNumber) : String.Empty); } break; case (Byte)IPProtocol.Udp: srcPort = (UInt16)(buffer[ipHeaderLength] << 8 | buffer[ipHeaderLength + 1]); dstPort = (UInt16)(buffer[ipHeaderLength + 2] << 8 | buffer[ipHeaderLength + 3]); /* * Console.Write("{0,9} | {1,2} {2,15} {3,15} | ", received, * ipHeaderLength, new IPAddress(srcAddress), new IPAddress(dstAddress)); * Console.WriteLine("Udp {0,5} > {1,-5}", srcPort, dstPort); */ break; default: IPProtocol protocolEnum = (IPProtocol)protocol; Console.Write("{0,-20} | {1,9} | {2,2} {3,15} {4,15} | ", DateTime.Now, received, ipHeaderLength, new IPAddress(srcAddress), new IPAddress(dstAddress)); Console.WriteLine(protocolEnum.ToString()); //Console.WriteLine("\r\n\r\n"); break; } } } }
public DeviceInfo() { devIPProtocol = IPProtocol.IPV4; devIP = System.Net.IPAddress.Any; }