Esempio n. 1
0
        /// <summary>
        /// Creates a new instance of WinComputer for 'localhost' using \root\CIMV2 namespace.
        /// </summary>
        public WMIBase()
        {
            m_ComputerName = "localhost";
            m_IPAddress = System.Net.IPAddress.Parse("127.0.0.1");

            SetScope();
        }
Esempio n. 2
0
        public IPPacket(ref byte[] Packet)
            : base()
        {
            try {
                Version = (byte)(Packet[0] >> 4);
                HeaderLength = (byte)((Packet[0] & 0x0F) * 4);
                TypeOfService = Packet[1];
                TotalLength = (ushort)System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 2));
                Identification = (ushort)System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 4));
                Flags = (byte)((Packet[6] & 0xE0) >> 5);
                FragmentOffset = (ushort)(System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 6)) & 0x1FFF);
                TimeToLive = Packet[8];
                Protocol = Packet[9];
                HeaderChecksum = (ushort)(System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 10)));
                SourceAddress = new System.Net.IPAddress(System.BitConverter.ToInt32(Packet, 12) & 0x00000000FFFFFFFF);
                DestinationAddress = new System.Net.IPAddress(System.BitConverter.ToInt32(Packet, 16) & 0x00000000FFFFFFFF);
                PacketData = new byte[TotalLength - HeaderLength];
                System.Buffer.BlockCopy(Packet, HeaderLength, PacketData, 0, PacketData.Length);
            } catch { }

            switch (Protocol) {
                case 1: ICMP = new ICMPPacket(ref PacketData); break;
                case 6: TCP = new TCPPacket(ref PacketData); break;
                case 17: UDP = new UDPPacket(ref PacketData); break;
            }
        }
Esempio n. 3
0
 /// <summary>
 /// 初始化接收消息队列
 /// </summary>
 /// <param name="msg">消息</param>
 /// <param name="ip">发送者IP</param>
 /// <param name="port">发送者端口</param>
 /// <param name="sender">发送者套接字对像</param>
 public UDPReceiveMessage(IMLibrary.Class.Msg msg, System.Net.IPAddress ip, int port, object sender)
 {
     this.Msg = msg;
     this.Ip = ip;
     this.Port = port;
     this.Sender = sender;
 }
Esempio n. 4
0
        internal Sockaddr(IntPtr sockaddrPtr)
        {
            // A sockaddr struct. We use this to determine the address family
            PcapUnmanagedStructures.sockaddr saddr;

            // Marshal memory pointer into a struct
            saddr = (PcapUnmanagedStructures.sockaddr)Marshal.PtrToStructure(sockaddrPtr,
                                                     typeof(PcapUnmanagedStructures.sockaddr));

            // record the sa_family for informational purposes
            _sa_family = saddr.sa_family;

            byte[] addressBytes;
            if (saddr.sa_family == Pcap.AF_INET)
            {
                type = Type.AF_INET_AF_INET6;
                PcapUnmanagedStructures.sockaddr_in saddr_in =
                    (PcapUnmanagedStructures.sockaddr_in)Marshal.PtrToStructure(sockaddrPtr,
                                                                                typeof(PcapUnmanagedStructures.sockaddr_in));
                ipAddress = new System.Net.IPAddress(saddr_in.sin_addr.s_addr);
            }
            else if (saddr.sa_family == Pcap.AF_INET6)
            {
                type = Type.AF_INET_AF_INET6;
                addressBytes = new byte[16];
                PcapUnmanagedStructures.sockaddr_in6 sin6 =
                    (PcapUnmanagedStructures.sockaddr_in6)Marshal.PtrToStructure(sockaddrPtr,
                                                         typeof(PcapUnmanagedStructures.sockaddr_in6));
                Array.Copy(sin6.sin6_addr, addressBytes, addressBytes.Length);
                ipAddress = new System.Net.IPAddress(addressBytes);
            }
            else if (saddr.sa_family == Pcap.AF_PACKET)
            {
                type = Type.HARDWARE;

                PcapUnmanagedStructures.sockaddr_ll saddr_ll =
                    (PcapUnmanagedStructures.sockaddr_ll)Marshal.PtrToStructure(sockaddrPtr,
                                                      typeof(PcapUnmanagedStructures.sockaddr_ll));

                byte[] hardwareAddressBytes = new byte[saddr_ll.sll_halen];
                for (int x = 0; x < saddr_ll.sll_halen; x++)
                {
                    hardwareAddressBytes[x] = saddr_ll.sll_addr[x];
                }
                hardwareAddress = new PhysicalAddress(hardwareAddressBytes); // copy into the PhysicalAddress class
            }
            else
            {
                type = Type.UNKNOWN;

                // place the sockaddr.sa_data into the hardware address just in case
                // someone wants access to the bytes
                byte[] hardwareAddressBytes = new byte[saddr.sa_data.Length];
                for (int x = 0; x < saddr.sa_data.Length; x++)
                {
                    hardwareAddressBytes[x] = saddr.sa_data[x];
                }
                hardwareAddress = new PhysicalAddress(hardwareAddressBytes);
            }
        }
Esempio n. 5
0
        public IPAddress(byte[] address)
        {
            if (address == null)
                throw new ArgumentNullException ("address");

            this.address = new System.Net.IPAddress (address);
        }
Esempio n. 6
0
		public Socks4Packet(byte[] packet, int startIndex, int count)
		{
			Version = packet[startIndex + 0];
			Command = packet[startIndex + 1];
			Port = ((int)(packet[startIndex + 2]) << 8) | packet[startIndex + 3];
			IPAddress = new System.Net.IPAddress(BitConverter.ToInt64(packet, startIndex + 4));
		}
Esempio n. 7
0
File: Domain.cs Progetto: staxgr/ops
        // If argument contains a "/" we assume it is on the form:  subnet-address/subnet-mask
        // In that case we loop over all interfaces and take the first one that matches
        // i.e. the one whos interface address is on the subnet
        public static string DoSubnetTranslation(string ip)
        {
            int index = ip.IndexOf('/');
            if (index < 0) return ip;

            string subnetIp = ip.Substring(0, index);
            string subnetMask = ip.Substring(index + 1);

            byte[] mask = System.Net.IPAddress.Parse(subnetMask).GetAddressBytes();

            System.Net.NetworkInformation.IPGlobalProperties computerProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

            if (nics != null && nics.Length > 0)
            {
                foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics)
                {
                    System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties();
                    System.Net.NetworkInformation.UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses;
                    if (uniCast == null) continue;

                    foreach (System.Net.NetworkInformation.UnicastIPAddressInformation uni in uniCast)
                    {
                        if (uni.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4
                        {
                            byte[] addr = uni.Address.GetAddressBytes();
                            for (int j = 0; j < addr.Length; j++) addr[j] = (byte)((int)addr[j] & (int)mask[j]);
                            string Subnet = new System.Net.IPAddress(addr).ToString();

                            if (Subnet.Equals(subnetIp))
                            {
                                return uni.Address.ToString();
                            }
                        }
                    }
                }
            }
            return subnetIp;

            //// This only works on Vista and later
            //System.Net.NetworkInformation.IPGlobalProperties gp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            //System.Net.NetworkInformation.UnicastIPAddressInformationCollection x = gp.GetUnicastAddresses();
            //for (int i = 0; i < x.Count; i++)
            //{
            //    if (x[i].Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4
            //    {
            //        byte[] addr = x[i].Address.GetAddressBytes();
            //        byte[] mask = x[i].IPv4Mask.GetAddressBytes();
            //        for (int j = 0; j < addr.Length; j++) addr[j] = (byte)((int)addr[j] & (int)mask[j]);
            //        string Subnet = new System.Net.IPAddress(addr).ToString();

            //        if (Subnet.Equals(subnetIp))
            //        {
            //            return x[i].Address.ToString();
            //        }
            //    }
            //}
            //return subnetIp;
        }
Esempio n. 8
0
 public ControlSettings(string HostName, string username, string password, string label)
 {
     System.Net.IPAddress[] addr = new System.Net.IPAddress[1];
     System.Net.IPAddress.TryParse(HostName, out _addrRdb);
     this._username = username;
     this._password = password;
     this._label = label;
 }
 public void ConnectToServer()
 {
     soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     //ipAdd = System.Net.IPAddress.Parse("10.1.70.50");
     ipAdd = System.Net.IPAddress.Parse("192.168.0.18");
     remoteEP = new System.Net.IPEndPoint(ipAdd, 1337);
     soc.Connect(remoteEP);
 }
Esempio n. 10
0
        public IPAddress(byte[] address, long scopeId)
        {
            if (address == null)
                throw new ArgumentNullException ("address");
            if (address.Length != 16)
                throw new ArgumentException ("An invalid IP address was specified.", "address");

            this.address = new System.Net.IPAddress (address, scopeId);
        }
        public EmbeddedServer(int port)
        {
            this.m_Port = port;
            this.m_IP = System.Net.IPAddress.Parse("127.0.0.1");
            this.m_WebSource = new Mono.WebServer.XSPWebSource(this.m_IP, port);

            this.m_ServerDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            this.m_ApplicationServer = new Mono.WebServer.ApplicationServer(this.m_WebSource, m_ServerDirectory);
        }
Esempio n. 12
0
		public RecordA(RecordReader rr)
		{
			Address = new System.Net.IPAddress(rr.ReadBytes(4));
			//System.Net.IPAddress.TryParse(string.Format("{0}.{1}.{2}.{3}",
			//	rr.ReadByte(),
			//	rr.ReadByte(),
			//	rr.ReadByte(),
			//	rr.ReadByte()), out this.Address);
		}
Esempio n. 13
0
        public RemoteClient(IUserClient localUser, System.Net.IPAddress IP, int port)
            : base(localUser)
        {
            this.HostIP = IP;
            this.Port = port;
            Handler = new ClientPacketHandler();

            Reader.OnReadData += Handler.OnRead;
            Reader.OnDisconnect += Reader_OnDisconnect;
            Reader.OnBufferOverflow += Reader_OnBufferOverflow;
        }
Esempio n. 14
0
 public RecordAAAA(RecordReader rr)
 {
     this.Address = System.Net.IPAddress.Parse(
         string.Format("{0:x}:{1:x}:{2:x}:{3:x}:{4:x}:{5:x}:{6:x}:{7:x}",
         rr.ReadUInt16(),
         rr.ReadUInt16(),
         rr.ReadUInt16(),
         rr.ReadUInt16(),
         rr.ReadUInt16(),
         rr.ReadUInt16(),
         rr.ReadUInt16(),
         rr.ReadUInt16())
     );
 }
Esempio n. 15
0
        public MyDroneServer() {
            this.server = BlakcMakiga.Abrakadubra.CreateInstance( BlakcMakiga.BlakcInstanceIdentifier.BlakcServer ) as BlakcMakiga.Net.IBlakcServer;
            this.server.ClientStatusChanged += Server_ClientStatusChanged;
            this.server.ClientDataReceived += Server_ClientDataReceived;

            this.Port = Defines.DEFAULT_DRONESERVER_LOCALPORT;
            this.LocalEndPoint = Defines.DEFAULT_DRONESERVER_LISTENERIP;

            this.packetGenerator = new MyDronePacketGenerator( BlakcMakiga.Utils.CRC.CRCMode.CRC16 );

            this.drones = new List<MyDrone>( 2 );

            this.sequenceCount = 0;
        }
Esempio n. 16
0
 public PrintService(System.IO.Stream stream, Dicom.Log.Logger log)
     : base(stream, log)
 {
     var pi = stream.GetType().GetProperty("Socket", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
     if (pi != null)
     {
         var endPoint = ((System.Net.Sockets.Socket)pi.GetValue(stream, null)).RemoteEndPoint as System.Net.IPEndPoint;
         RemoteIP = endPoint.Address;
     }
     else
     {
         RemoteIP = new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 });
     }
 }
Esempio n. 17
0
        public Network(NetworkSettings sett)
        {
            if (sett.address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                throw new ArgumentException("Address must be a IPv4 address");
            if (sett.netmask.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                throw new ArgumentException("Netmask must be a IPv4 netmask");
            if (!IsValidNetmask(sett.netmask))
                throw new ArgumentException("Netmask is not a valid netmask");

            this.netmask = sett.netmask;
            this.address = ApplyNetmask(sett.address, sett.netmask);

            if (!IsValidIPv4Address(this.address))
                throw new ArgumentException("Address is not a valid IPv4 address");
        }
Esempio n. 18
0
        public ConfigForm(System.Net.IPAddress defaultIPLocal, int defaultPortLocal, System.Net.IPAddress defaultIPSQL, int defaultPortSQL)
        {
            InitializeComponent();

            // Set the internal default and text boxes.
            ipAddressServer = defaultIPLocal;
            port = defaultPortLocal;
            localIpTextBox.Text = ipAddressServer.ToString();
            localPortTextBox.Text = port.ToString();

            ipAddressSQL = defaultIPSQL;
            portSQL = defaultPortSQL;

            DialogResult = System.Windows.Forms.DialogResult.Cancel; // Assume cancel until ok button is pressed.
        }
Esempio n. 19
0
 // Methods
 public RealmLogonResponse(byte[] data)
     : base(data)
 {
     this.realmServerPort = -1;
     this.cookie = BitConverter.ToUInt32(data, 3);
     if (base.Data.Length < 0x4a)
     {
         this.result = (RealmLogonResult)BitConverter.ToUInt32(data, 7);
     }
     else
     {
         this.result = RealmLogonResult.Success;
         this.realmServerIP = new System.Net.IPAddress((long)BitConverter.ToUInt32(data, 0x13));
         this.realmServerPort = BEBitConverter.ToUInt16(data, 0x17);
         this.username = ByteConverter.GetNullString(data, 0x4b);
         //this.unknown = BitConverter.ToUInt16(data, 0x4c + this.username.Length);
     }
 }
Esempio n. 20
0
        public Network(System.Net.IPAddress address, int prefixlen)
        {
            if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                throw new ArgumentException("Address must be a IPv4 address");
            if (prefixlen < 0 || prefixlen > 32)
                throw new ArgumentOutOfRangeException("Prefixlength must be an integer between 0 and 32 inclusive");

            byte[] bytes = new byte[4];
            for (int i = 0; i < prefixlen / 8; ++i)
                bytes[i] = 0xFF;
            for (int i = 0; i < prefixlen % 8; ++i)
                bytes[prefixlen / 8] |= Convert.ToByte(1 << (7 - i));

            netmask = new System.Net.IPAddress(bytes);

            this.address = ApplyNetmask(address, netmask);

            if (!IsValidIPv4Address(this.address))
                throw new ArgumentException("Address is not a valid IPv4 address");
        }
Esempio n. 21
0
        public void Connect(System.String HostName)
        {
            //prntSome.printSome("Connect");
            System.Int32           port    = 10012;
            System.Net.IPAddress addrRdb;
            System.Net.IPAddress[] addr = new System.Net.IPAddress[1];
            if (System.Net.IPAddress.TryParse(HostName, out addrRdb))
            {
                //must do push ip to array here
            }
            else
            {
                //System.Net.IPHostEntry IPHost = System.Net.Dns.GetHostEntry(HostName);
                //System.Net.IPAddress[] addr = IPHost.AddressList;
            }
            addr[0] = addrRdb;

            try
            {
                this.runOffline = false;
                // Create New Socket
                this.CurSocket = new System.Net.Sockets.Socket (
                    System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream,
                    System.Net.Sockets.ProtocolType.Tcp);

                // Create New EndPoint
                System.Net.IPEndPoint iep  = new System.Net.IPEndPoint(addr[0],port);

                // This is a non blocking IO
                this.CurSocket.Blocking        = false ;

                // Begin Asyncronous Connection
                this.CurSocket.BeginConnect (iep,  new System.AsyncCallback (ConnectCallback), CurSocket) ;
            }
            catch (System.Exception CurException)
            {
                this.runOffline = true;
                System.Console.WriteLine ("Connect: " + CurException.Message);
            }
        }
Esempio n. 22
0
		/* Methods */
		/// <summary>
		/// TCP provider constructor
		/// </summary>
		/// <param name="lcm">LCM object</param>
		/// <param name="up">URL parser object</param>
		public TCPProvider(LCM lcm, URLParser up)
		{
			this.lcm = lcm;
			
			string[] addrport = up.Get("network", DEFAULT_NETWORK).Split(':');
			if (addrport.Length == 1)
			{
				inetAddr = System.Net.Dns.GetHostAddresses(addrport[0])[0];
				inetPort = 7700;
			}
			else if (addrport.Length == 2)
			{
				inetAddr = System.Net.Dns.GetHostAddresses(addrport[0])[0];
				inetPort = Int32.Parse(addrport[1]);
			}
			else
			{
				Console.Error.WriteLine("TCPProvider: Don't know how to parse " + up.Get("network", DEFAULT_NETWORK));
				Environment.Exit(-1);
			}
			
			reader = new ReaderThread(this);
			reader.Start();
		}
Esempio n. 23
0
 /// <summary>
 /// ���Ŀ��ƶ�(��������)
 /// </summary>
 /// <param name="serverAddress"></param>
 private void change(object serverAddress)
 {
     if (curServerIP == null)
         curServerIP = (System.Net.IPAddress)serverAddress;
     InsertControler((System.Net.IPAddress)serverAddress, false);
     if (currentControler != null)
         currentControler.Run();
 }
Esempio n. 24
0
        private int WinsockConnectDetour(IntPtr s, IntPtr addr, int addrsize)
        {
            lock (winsockLock)
            {
                System.Diagnostics.Debugger.Launch();
                if (_settings.ProxyIP != null && _settings.ProxyIP != "")
                {
                    var proxyip = _settings.ProxyIP.Split(':').ToList();
                    if (proxyip.Count() != 2)
                    {
                        Utility.Log("Proxy ip not valid format");
                        closesocket(s);
                        return(-1);
                    }

                    ////Get EVE IP
                    sockaddr_in structure = (sockaddr_in)Marshal.PtrToStructure(addr, typeof(sockaddr_in));
                    string      eveIp     = new System.Net.IPAddress(structure.sin_addr.S_addr).ToString();
                    ushort      evePort   = ntohs(structure.sin_port);

                    ////Connect to Socks5 server
                    SetAddr(s, addr, proxyip[0], proxyip[1]);
                    var result = Connect(s, addr, addrsize);
                    if (result == -1)
                    {
                        return(-1);
                    }

                    ////Send Protocol Socks5
                    IntPtr socksProtocolRequest = SetUpSocks5Request();
                    result = send(s, socksProtocolRequest, 4, 0);
                    if (result == -1)
                    {
                        return(-1);
                    }

                    ////Response
                    var response = Recieve(s, 2);
                    if (response == IntPtr.Zero)
                    {
                        return(-1);
                    }

                    byte[] recvBytes = new byte[2] {
                        Marshal.ReadByte(response), Marshal.ReadByte(response, 1)
                    };
                    if (recvBytes[1] == 255)
                    {
                        Utility.Log("No authentication method was accepted by the proxy server");
                        return(-1);
                    }
                    if (recvBytes[0] != 5)
                    {
                        Utility.Log("No SOCKS5 proxy");
                        return(-1);
                    }

                    ////If authenticaterequest response, send authenicate request
                    if (recvBytes[1] == 2)
                    {
                        int length = 0;
                        var authenticateRequest = SetUpAuthenticateRequest(_settings.ProxyUsername, _settings.ProxyPassword, out length);
                        result = Send(s, authenticateRequest, length);

                        ////Response
                        response = Recieve(s, 2);
                        if (response == IntPtr.Zero)
                        {
                            return(-1);
                        }

                        recvBytes = new byte[2] {
                            Marshal.ReadByte(response), Marshal.ReadByte(response, 1)
                        };
                        if (recvBytes[1] != 0)
                        {
                            Utility.Log("Proxy: incorrect username/password");
                            return(-1);
                        }
                    }

                    ////Request bind with eve server
                    var bindRequest = SetUpBindWithEve(eveIp, evePort);
                    result = Send(s, bindRequest, 10);
                    if (result == -1)
                    {
                        return(-1);
                    }
                    ////Reponse
                    response = Recieve(s, 10);
                    if (response == IntPtr.Zero)
                    {
                        return(-1);
                    }
                    if (!VerifyBindResponse(response))
                    {
                        return(-1);
                    }

                    ////Setup success
                    WSASetLastError(0);
                    SetLastError(0);

                    ////Clean memory
                    foreach (var ptr in allocatedMemory)
                    {
                        Marshal.FreeHGlobal(ptr);
                    }

                    allocatedMemory.Clear();
                    return(0);
                }
                else
                {
                    var result = connect(s, addr, addrsize);
                    return(result);
                }
            }
        }
 public static bool IsIPAddress(this string ipAddress)
 {
     System.Net.IPAddress address = null;
     return(System.Net.IPAddress.TryParse(ipAddress, out address));
 }
Esempio n. 26
0
        /// <summary>
        /// The main thread of the ftp server
        /// Listen and acception clients, create handler threads for each client
        /// </summary>
        private void ThreadRun()
        {
            FtpServerMessageHandler.Message += TraceMessage;

            // listen at the port by the "FTP" endpoint setting
            int port = int.Parse(ConfigurationManager.AppSettings["FTP"]);

            System.Net.IPAddress  ipaddr     = SocketHelpers.GetLocalAddress();
            System.Net.IPEndPoint ipEndPoint = new System.Net.IPEndPoint(ipaddr.Address, port);
            FtpServer.m_ftpIpAddr = ipaddr.ToString();
            m_socketListen        = SocketHelpers.CreateTcpListener(ipEndPoint);

            if (m_socketListen != null)
            {
                string msg = string.Format("FTP Server started.Listening to: {0}", ipEndPoint);
                FtpServer.LogWrite(msg);
                Trace.TraceInformation(msg);

                m_socketListen.Start();

                bool fContinue = true;

                while (fContinue)
                {
                    TcpClient socket = null;

                    try
                    {
                        socket = m_socketListen.AcceptTcpClient();
                    }
                    catch (SocketException)
                    {
                        fContinue = false;
                    }
                    finally
                    {
                        if (socket == null)
                        {
                            fContinue = false;
                        }
                        else if (m_apConnections.Count >= m_maxClients)
                        {
                            Trace.WriteLine("Too many clients, won't handle this connection", "Warnning");
                            SendRejectMessage(socket);
                            socket.Close();
                        }
                        else
                        {
                            socket.NoDelay = false;

                            m_nId++;

                            FtpServerMessageHandler.SendMessage(m_nId, "New connection");

                            SendAcceptMessage(socket);
                            // 2015-11-25 cljung : under stress testing, this happens. Don't know why yet, but let's keep it from crashing
                            try
                            {
                                InitialiseSocketHandler(socket);
                            }
                            catch (System.ObjectDisposedException ode)
                            {
                                Trace.TraceError(string.Format("ObjectDisposedException initializing client socket:\r\n{0}", ode));
                                m_nId--;
                                // can't fail
                                try {
                                    socket.Close();
                                } catch { }
                            }
                        }
                    }
                }
            }
            else
            {
                FtpServerMessageHandler.SendMessage(0, "Error in starting FTP server");
            }
        }
Esempio n. 27
0
        //Scan Method
        public void Scan()
        {
            ActionButtonSwich(); /* Scan */

            RTBClear();

            //Source Address
            string SourceAddress = this.SourceText.Text;

            //Time Out
            int TimeOut = 0;

            Int32.TryParse(this.TimeOutText.Text, out TimeOut);

            if (this.TimeOutText.Text.Contains(' '))
            {
                RTBAppendText("[Error] Invalid Timeout Expression!" + "\n", TextColors.Black);

                TimeOut = 0; /* Set to Default Timeout */
            }

            if (TimeOut == 0)
            {
                TimeOut = 1000;

                RTBAppendText("Timeout Set to 1000ms (Default)" + " \n", TextColors.Black);

                RTBRefresh();
            }

            else
            {
                RTBAppendText("Timeout Set to " + TimeOut.ToString() + "ms" + "\n", TextColors.Black);
            }

            //Destination Address
            string DestAddress = this.DestText.Text;

            //# Validation #
            bool SourceValidation = IPValidation(SourceAddress);

            bool DestValidation = IPValidation(DestAddress);

            if ((SourceValidation == false) || (DestValidation == false))
            {
                RTBAppendText("Source Address: " + SourceAddress + "\n", TextColors.Black);

                RTBAppendText("Destination Address: " + DestAddress + "\n", TextColors.Black);

                RTBAppendText("[Error] Invalid Source or Destination Addresses!" + "\n", TextColors.Black);

                RTBRefresh();
            }

            else
            {
                long SourceLong = Convert.ToInt64(SourceAddress.Replace(".", ""));

                long DestLong = Convert.ToInt64(DestAddress.Replace(".", ""));

                if (SourceLong >= DestLong)
                {
                    RTBAppendText("Source Address: " + SourceAddress + "\n", TextColors.Black);

                    RTBAppendText("Destination Address: " + DestAddress + "\n", TextColors.Black);

                    RTBAppendText("[Error] Invalid IP Addresses Range!" + "\n", TextColors.Black);

                    RTBRefresh();
                }

                else
                {
                    //Fix IP Address Format

                    //Source
                    string[] SourceSplit      = SourceAddress.Split('.');
                    string   SourceOctetOne   = IPFixFormat(SourceSplit[0]);
                    string   SourceOctetTwo   = IPFixFormat(SourceSplit[1]);
                    string   SourceOctetThree = IPFixFormat(SourceSplit[2]);
                    string   SourceOctetFour  = IPFixFormat(SourceSplit[3]);
                    SourceAddress = SourceOctetOne + "." + SourceOctetTwo + "." + SourceOctetThree + "." + SourceOctetFour; /* Modify Source Address */
                    System.Net.IPAddress SourceIP = System.Net.IPAddress.Parse(SourceAddress);                              /* Source IP */

                    //Destination
                    string[] DestSplit      = DestAddress.Split('.');
                    string   DestOctetOne   = IPFixFormat(DestSplit[0]);
                    string   DestOctetTwo   = IPFixFormat(DestSplit[1]);
                    string   DestOctetThree = IPFixFormat(DestSplit[2]);
                    string   DestOctetFour  = IPFixFormat(DestSplit[3]);
                    DestAddress = DestOctetOne + "." + DestOctetTwo + "." + DestOctetThree + "." + DestOctetFour; /* Modify Destination Address */
                    System.Net.IPAddress DestIP = System.Net.IPAddress.Parse(DestAddress);                        /* Destination IP */

                    Byte[] SourceBytes = SourceIP.GetAddressBytes();

                    while (true)
                    {
                        SourceBytes[3] = (byte)(SourceBytes[3] + 1); /* 4th Octet */

                        if (SourceBytes[3] == 0)
                        {
                            SourceBytes[2] = (byte)(SourceBytes[2] + 1); /* 3rd Octet */

                            if (SourceBytes[2] == 0)
                            {
                                SourceBytes[1] = (byte)(SourceBytes[1] + 1); /* 2nd Octet */

                                if (SourceBytes[1] == 0)
                                {
                                    SourceBytes[0] = (byte)(SourceBytes[0] + 1); /* 1st Octet */
                                }
                            }
                        }

                        string CurrentAddress = SourceBytes[0].ToString() + "." + SourceBytes[1].ToString() + "." + SourceBytes[2].ToString() + "." + SourceBytes[3].ToString();

                        //Test Communication
                        Ping Pinger = new Ping();

                        PingReply Reply = Pinger.Send(CurrentAddress, TimeOut);

                        if (Reply.Status == IPStatus.Success)
                        {
                            RTBAppendText("[" + CurrentAddress + "]" + " Connection Established!" + "\n", TextColors.Green);
                        }

                        else
                        {
                            RTBAppendText("[" + CurrentAddress + "]" + " Device is Unavailable!" + "\n", TextColors.Red);
                        }

                        Pinger.Dispose();

                        RTBRefresh();

                        if (CurrentAddress == DestAddress)
                        {
                            break;                                  /* Break Condition */
                        }
                    }
                }
            }

            RTBAppendText("Finished!" + "\n", TextColors.Black);

            ActionButtonSwich(); /* Stop */
        }
 /// <summary>
 /// <param name="ip">发送数据方的IP地址</param>
 /// <param name="port">发送数据方的端口号</param>
 /// </summary>
 public DataArrivalEventArgs(System.Net.IPAddress ip, int port)
 {
     this.IP = ip;
     this.Port = port;
 }
Esempio n. 29
0
        /// <overloads>this method has 2 overloads</overloads>
        /// <summary>
        /// Connects to the specified server and port, when the connection fails
        /// the next server in the list will be used.
        /// </summary>
        /// <param name="addresslist">List of servers to connect to</param>
        /// <param name="port">Portnumber to connect to</param>
        /// <exception cref="CouldNotConnectException">The connection failed</exception>
        /// <exception cref="AlreadyConnectedException">If there is already an active connection</exception>
        public void Connect(string[] addresslist, int port)
        {
            if (_IsConnected)
            {
                throw new AlreadyConnectedException("Already connected to: " + Address + ":" + Port);
            }

#if LOG4NET
            Logger.Connection.Info("connecting...");
#endif
            _ConnectTries++;
            _AddressList = (string[])addresslist.Clone();
            _Port        = port;

            if (OnConnecting != null)
            {
                OnConnecting(this, EventArgs.Empty);
            }
            try {
                System.Net.IPAddress ip = System.Net.Dns.Resolve(Address).AddressList[0];
                _TcpClient         = new IrcTcpClient();
                _TcpClient.NoDelay = true;
                _TcpClient.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                // set timeout, after this the connection will be aborted
                _TcpClient.ReceiveTimeout = _SocketReceiveTimeout * 1000;
                _TcpClient.SendTimeout    = _SocketSendTimeout * 1000;
                _TcpClient.Connect(ip, port);

                _Reader = new StreamReader(_TcpClient.GetStream(), _Encoding);
                _Writer = new StreamWriter(_TcpClient.GetStream(), _Encoding);

                if (_Encoding.GetPreamble().Length > 0)
                {
                    // HACK: we have an encoding that has some kind of preamble
                    // like UTF-8 has a BOM, this will confuse the IRCd!
                    // Thus we send a \r\n so the IRCd can safely ignore that
                    // garbage.
                    _Writer.WriteLine();
                }

                // Connection was succeful, reseting the connect counter
                _ConnectTries = 0;

                // updating the connection error state, so connecting is possible again
                IsConnectionError = false;
                _IsConnected      = true;

                // lets power up our threads
                _ReadThread.Start();
                _WriteThread.Start();
                _IdleWorkerThread.Start();

#if LOG4NET
                Logger.Connection.Info("connected");
#endif
                if (OnConnected != null)
                {
                    OnConnected(this, EventArgs.Empty);
                }
            } catch (Exception e) {
                if (_Reader != null)
                {
                    try {
                        _Reader.Close();
                    } catch (ObjectDisposedException) {
                    }
                }
                if (_Writer != null)
                {
                    try {
                        _Writer.Close();
                    } catch (ObjectDisposedException) {
                    }
                }
                if (_TcpClient != null)
                {
                    _TcpClient.Close();
                }
                _IsConnected      = false;
                IsConnectionError = true;

#if LOG4NET
                Logger.Connection.Info("connection failed: " + e.Message);
#endif
                if (_AutoRetry &&
                    _ConnectTries <= 3)
                {
                    if (OnAutoConnectError != null)
                    {
                        OnAutoConnectError(this, new AutoConnectErrorEventArgs(Address, Port, e));
                    }
#if LOG4NET
                    Logger.Connection.Debug("delaying new connect attempt for " + _AutoRetryDelay + " sec");
#endif
                    Thread.Sleep(_AutoRetryDelay * 1000);
                    _NextAddress();
                    Connect(_AddressList, _Port);
                }
                else
                {
                    throw new CouldNotConnectException("Could not connect to: " + Address + ":" + Port + " " + e.Message, e);
                }
            }
        }
 public static System.Threading.Tasks.Task <System.Net.IPHostEntry> GetHostEntryAsync(System.Net.IPAddress address)
 {
     throw null;
 }
Esempio n. 31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WebSocketServer"/> class that listens for incoming connection attempts
 /// on the specified <paramref name="address"/>, <paramref name="port"/> and <paramref name="secure"/>.
 /// </summary>
 /// <param name="address">
 /// A <see cref="System.Net.IPAddress"/> that contains an IP address.
 /// </param>
 /// <param name="port">
 /// An <see cref="int"/> that contains a port number.
 /// </param>
 /// <param name="secure">
 /// A <see cref="bool"/> that indicates providing a secure connection or not. (<c>true</c> indicates providing a secure connection.)
 /// </param>
 public WebSocketServer(System.Net.IPAddress address, int port, bool secure)
     : base(address, port, "/", secure)
 {
     init();
 }
 public static System.Net.IPHostEntry GetHostEntry(System.Net.IPAddress address)
 {
     throw null;
 }
 public static System.IAsyncResult BeginGetHostEntry(System.Net.IPAddress address, System.AsyncCallback?requestCallback, object?stateObject)
 {
     throw null;
 }
Esempio n. 34
0
 public AjaxLifeHttpServer(IpAddress addr, int port)
 {
     Address = addr;
     Port    = port;
     server  = new HttpServer.HttpServer();
 }
Esempio n. 35
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         DataLinkLayerReference = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 3)
     {
         IPAddress = new System.Net.IPAddress(BitConverter.GetBytes(Convert.ToUInt32(e.Value))).ToString();
     }
     else if (e.Index == 4)
     {
         List <uint> data = new List <uint>();
         if (e.Value != null)
         {
             if (e.Value is object[])
             {
                 foreach (object it in (object[])e.Value)
                 {
                     data.Add(Convert.ToUInt16(it));
                 }
             }
             else if (e.Value is ushort[])
             {
                 //Some meters are returning wrong data here.
                 foreach (ushort it in (ushort[])e.Value)
                 {
                     data.Add(it);
                 }
             }
         }
         MulticastIPAddress = data.ToArray();
     }
     else if (e.Index == 5)
     {
         List <GXDLMSIp4SetupIpOption> data = new List <GXDLMSIp4SetupIpOption>();
         if (e.Value != null)
         {
             foreach (object[] it in (object[])e.Value)
             {
                 GXDLMSIp4SetupIpOption item = new GXDLMSIp4SetupIpOption();
                 item.Type   = (Ip4SetupIpOptionType)Convert.ToInt32(it[0]);
                 item.Length = Convert.ToByte(it[1]);
                 item.Data   = (byte[])it[2];
                 data.Add(item);
             }
         }
         IPOptions = data.ToArray();
     }
     else if (e.Index == 6)
     {
         SubnetMask = Convert.ToUInt32(e.Value);
     }
     else if (e.Index == 7)
     {
         GatewayIPAddress = Convert.ToUInt32(e.Value);
     }
     else if (e.Index == 8)
     {
         UseDHCP = Convert.ToBoolean(e.Value);
     }
     else if (e.Index == 9)
     {
         PrimaryDNSAddress = Convert.ToUInt32(e.Value);
     }
     else if (e.Index == 10)
     {
         SecondaryDNSAddress = Convert.ToUInt32(e.Value);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="message"></param>
 /// <param name="ip"></param>
 /// <param name="port"></param>
 public DataArrivalEventArgs( Msg message, System.Net.IPAddress ip, int port)
 {
     this.msg = message;
     this.IP = ip;
     this.Port = port;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="WebSocketServer"/> class with
 /// the specified <paramref name="address"/> and <paramref name="port"/>.
 /// </summary>
 /// <remarks>
 ///   <para>
 ///   The new instance listens for the incoming handshake requests on
 ///   <paramref name="address"/> and <paramref name="port"/>.
 ///   </para>
 ///   <para>
 ///   It provides secure connections if <paramref name="port"/> is 443.
 ///   </para>
 /// </remarks>
 /// <param name="address">
 /// A <see cref="System.Net.IPAddress"/> that represents the local IP address
 /// for the server.
 /// </param>
 /// <param name="port">
 /// An <see cref="int"/> that represents the port number on which to listen.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="address"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// <paramref name="address"/> is not a local IP address.
 /// </exception>
 /// <exception cref="ArgumentOutOfRangeException">
 /// <paramref name="port"/> is less than 1 or greater than 65535.
 /// </exception>
 public WebSocketServer(System.Net.IPAddress address, int port)
     : this(address, port, port == 443)
 {
 }
Esempio n. 38
0
        public static int socketCom()
        {
            //ListenするIPの指定
            string IP_String = "0.0.0.0";

            System.Net.IPAddress IP_Address = System.Net.IPAddress.Parse(IP_String);

            //Listenするport番号
            int PORT = 5000;

            //TcpListenerオブジェクトの作成
            System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(IP_Address, PORT);

            //Listenを開始
            listener.Start();
//            Console.WriteLine("Listenを開始しました({0}:{1})", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address,((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求のチェック,受け入れ
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();

/*            Console.WriteLine("クライアント({0}:{1})と接続しました。",
 *              ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
 *              ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);
 */
            //NetworkStreamを取得
            System.Net.Sockets.NetworkStream ns = client.GetStream();

            //読み取り、書き込みのタイムアウトを10秒にする
            //デフォルトはInfiniteで、タイムアウトしない
            //(.NET Framework 2.0以上が必要)
            ns.ReadTimeout  = 10000;
            ns.WriteTimeout = 10000;

            //クライアントから送られたデータを受信する
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            bool disconnected        = false;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes           = new byte[256];
            int    resSize            = 0;

            StreamReader sr     = new StreamReader(ns, enc);
            string       resMsg = String.Empty;

            string[] values = new string[3];
            do
            {
                resMsg = sr.ReadLine();
                if (resMsg == null)
                {
                    break;
                }
                Console.WriteLine(resMsg);

                values = resMsg.Split(' ');
                switch (values[0])
                {
                case "theta:":
                    thetaFromAndroid = double.Parse(values[1]);
                    break;

                case "dist:":
                    distFromAndroid = double.Parse(values[1]);
                    break;

                case "lean:":

                    break;

                default:
                    break;
                }
            } while (true);


            //受信したデータを文字列に変換
            resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
            //末尾の\nを削除
            resMsg = resMsg.TrimEnd('\n');
            Console.WriteLine(resMsg);
            //閉じる
            ms.Close();
            ns.Close();
            client.Close();
//            Console.WriteLine("クライアントとの接続を閉じました。");

            //リスナを閉じる
            listener.Stop();
//            Console.WriteLine("Listenerを閉じました。");

            Console.ReadLine();
            return(1);   //規定文字が来たら,-1などを返すようにあとで変える
        }
Esempio n. 39
0
        /// <summary>
        /// handles the log Update, call in a new thread to reduce performance impacts on the service handling.
        /// </summary>
        /// <param name="msg">Message which was sent from the Syslog Client</param>
        /// <param name="ipSourceAddress">Source IP of the Syslog Sender</param>
        /// <param name="receiveTime">Receive Time of the Syslog Message</param>
        private static void LogToFile(string msg, System.Net.IPAddress ipSourceAddress, System.DateTime receiveTime)
        {
            Log log = new Log();

            log.WriteToLog($"{msg}; {ipSourceAddress}; {receiveTime}\n", logFile);
        }
Esempio n. 40
0
 public IPEndPoint(System.Net.IPAddress address, int port)
 {
 }
Esempio n. 41
0
 public void AddIpAddress(System.Net.IPAddress ipAddress)
 {
 }
Esempio n. 42
0
 public SasIPRange(System.Net.IPAddress start, System.Net.IPAddress end = null)
 {
     throw null;
 }
Esempio n. 43
0
        protected override void OnReceive(Session aSession, string aName, string aValue)
        {
            switch (aName)
            {
            case "DeviceButton1":
            case "DeviceButton2":
            case "DeviceButton3":
            case "DeviceButton4":
            case "DeviceButton5":
                string s      = aName.Replace("DeviceButton", "");
                int    button = Convert.ToInt32(s);
                iMacAddress = iBoxSelection.MacAddressOfButton(button);
                if (iMacAddress.Length > 0)
                {
                    SetSelected(aSession);
                    iBoxSelection.SetSelectedBox(iMacAddress);
                    iBoxSelection.ShowButtons();

                    Box    box         = ModelInstance.Instance.Network.Box(iMacAddress);
                    string deviceIpStr = box.IpAddress;
                    System.Net.IPAddress interfaceIp = box.NetworkInterfaceIpAddress();
                    ModelInstance.Instance.Network.SetNetworkInterface(interfaceIp);
                    string interfaceIpStr = interfaceIp.ToString();
                    ModelInstance.Instance.Diagnostics.Run(ETest.eMulticastFromDs, interfaceIpStr, deviceIpStr);
                    ModelInstance.Instance.Diagnostics.Run(ETest.eMulticastToDs, interfaceIpStr, deviceIpStr);
                    ModelInstance.Instance.Diagnostics.Run(ETest.eUdpEcho, interfaceIpStr, deviceIpStr);
                    ModelInstance.Instance.Diagnostics.Run(ETest.eTcpEcho, interfaceIpStr, deviceIpStr);
                }
                break;

            case "Refresh":
                ModelInstance.Instance.Network.Refresh();

                Send("Disable", "TroubleshootButton");
                Send("Disable", "PreviousButton");
                Send("Disable", "NavTab1");

                Send("Hide", "RefreshButton");
                Send("Unhide", "DiscoveryRefreshSpinner");
                Thread.Sleep(4000);
                ShowDeviceList();
                Send("Hide", "DiscoveryRefreshSpinner");
                Send("Unhide", "RefreshButton");

                Send("Enable", "TroubleshootButton");
                Send("Enable", "PreviousButton");
                Send("Enable", "NavTab1");

                break;

            case "PageUp":
                iBoxSelection.PreviousButtonPage();
                iBoxSelection.ShowButtons();
                break;

            case "PageDown":
                iBoxSelection.NextButtonPage();
                iBoxSelection.ShowButtons();
                break;

            case "ListChange":
                iRxMutex.WaitOne();
                switch (aValue)
                {
                case "Added":
                    iListCount++;
                    break;

                case "Removed":
                    iListCount--;
                    break;

                case "Cleared":
                    Console.WriteLine("SelectionChange {0} count {1}", aValue, iListCount);
                    iListCount = 0;
                    break;
                }
                iRxMutex.ReleaseMutex();
                break;

            default:


                base.OnReceive(aSession, aName, aValue);
                break;
            }
        }
Esempio n. 44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpServer"/> class with
 /// the specified <paramref name="address"/> and <paramref name="port"/>.
 /// </summary>
 /// <remarks>
 ///   <para>
 ///   An instance initialized by this constructor listens for the incoming requests on
 ///   <paramref name="address"/> and <paramref name="port"/>.
 ///   </para>
 ///   <para>
 ///   If <paramref name="port"/> is 443, that instance provides a secure connection.
 ///   </para>
 /// </remarks>
 /// <param name="address">
 /// A <see cref="System.Net.IPAddress"/> that represents the local IP address of the server.
 /// </param>
 /// <param name="port">
 /// An <see cref="int"/> that represents the port number on which to listen.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="address"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// <paramref name="address"/> isn't a local IP address.
 /// </exception>
 /// <exception cref="ArgumentOutOfRangeException">
 /// <paramref name="port"/> isn't between 1 and 65535 inclusive.
 /// </exception>
 public HttpServer(System.Net.IPAddress address, int port)
     : this(address, port, port == 443)
 {
 }
Esempio n. 45
0
        /// <summary>
        /// An extension method to determine if an IP address is internal, as specified in RFC1918
        /// </summary>
        /// <param name="ip">The IP address that will be tested</param>
        /// <returns>Returns true if the IP is internal, false if it is external</returns>
        public static bool IsInternal(this System.Net.IPAddress ip)
        {
            if (ip.IsIPv4MappedToIPv6)
            {
                ip = ip.MapToIPv4();
            }
            if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                byte[] bytes = ip.GetAddressBytes();
                switch (bytes[0])
                {
                case 10:
                case 127:
                    return(true);

                case 172:
                    return(bytes[1] >= 16 && bytes[1] < 32);

                case 192:
                    return(bytes[1] == 168);

                default:
                    return(bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0 && bytes[3] == 0);
                }
            }

            string addressAsString = ip.ToString();
            string firstWord       = addressAsString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[0];

            // equivalent of 127.0.0.1 in IPv6
            if (addressAsString == "::1")
            {
                return(true);
            }

            // The original IPv6 Site Local addresses (fec0::/10) are deprecated. Unfortunately IsIPv6SiteLocal only checks for the original deprecated version:
            else if (ip.IsIPv6SiteLocal)
            {
                return(true);
            }

            // These days Unique Local Addresses (ULA) are used in place of Site Local.
            // ULA has two variants:
            //      fc00::/8 is not defined yet, but might be used in the future for internal-use addresses that are registered in a central place (ULA Central).
            //      fd00::/8 is in use and does not have to registered anywhere.
            else if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fc")
            {
                return(true);
            }
            else if (firstWord.Length >= 4 && firstWord.Substring(0, 2) == "fd")
            {
                return(true);
            }
            // Link local addresses (prefixed with fe80) are not routable
            else if (firstWord == "fe80")
            {
                return(true);
            }
            // Discard Prefix
            else if (firstWord == "100")
            {
                return(true);
            }

            // Any other IP address is not Unique Local Address (ULA)
            return(false);
        }
Esempio n. 46
0
 private static string convertToString(System.Net.IPAddress address)
 {
     return(address.AddressFamily == AddressFamily.InterNetworkV6
            ? String.Format("[{0}]", address.ToString())
            : address.ToString());
 }
Esempio n. 47
0
 private void btnStart_Click(object sender, EventArgs e)
 {
     txtStatus.Text += "Server starting...";
     System.Net.IPAddress ip = System.Net.IPAddress.Parse(txtHost.Text);
     server.Start(ip, Convert.ToInt32(txtPort.Text));
 }
 public void DropMulticastGroup(System.Net.IPAddress multicastAddr, int ifindex)
 {
 }
Esempio n. 49
0
 // Methods
 public BnetConnectionRequest(byte[] data)
     : base(data)
 {
     this.protocol = BitConverter.ToUInt32(data, 3);
     this.platform = (BattleNetPlatform) BitConverter.ToUInt32(data, 7);
     this.client = (BattleNetClient) BitConverter.ToUInt32(data, 11);
     this.version = BitConverter.ToUInt32(data, 15);
     this.language = BitConverter.ToUInt32(data, 0x13);
     this.localIP = new System.Net.IPAddress((long)BitConverter.ToUInt32(data, 0x17));
     this.timeZoneBias = BitConverter.ToUInt32(data, 0x1b);
     this.localeID = BitConverter.ToUInt32(data, 0x1f);
     this.languageID = BitConverter.ToUInt32(data, 0x23);
     this.countryAbbreviation = ByteConverter.GetNullString(data, 0x27);
     this.countryName = ByteConverter.GetNullString(data, 40 + this.countryAbbreviation.Length);
 }
 public void Connect(System.Net.IPAddress addr, int port)
 {
 }
Esempio n. 51
0
 /// <summary>
 /// ���һ�����ƶ�
 /// </summary>
 /// <param name="serverAddress">����˵�ַ</param>
 /// <param name="insertIntoTreeNode">�Ƿ���ӵ������б���</param>
 /// <returns>���οؼ��Ľ���� �� �Ѿ����ӵķ������ �Ƿ�ƥ��</returns>
 private bool InsertControler(System.Net.IPAddress serverAddress,bool insertIntoTreeNode)
 {
     DisplayMessage("��������" + serverAddress + "...");
     //������Դ���10
     BaseControler mainControler = new BaseControler(serverAddress, Constant.Port_Main, 10);
     mainControler.Execute = new ExecuteCodeEvent(mainExecuteCode);
        // mainControler.MaxTimes = Constant.MaxTimes;
     mainControler.Connecting();
     if (mainControler.HaveConnected)
     {
         DisplayMessage("����" + serverAddress + "�ɹ�!");
         currentControler = mainControler;
         curServerIP = mainControler.ServerAddress;
         //�Ƿ���ӵ������б���
         if (insertIntoTreeNode)
         {
             try
             {
                 trv_HostView.Invoke(new TreeViewAddEvent(TreeViewAddNode), new object[] { serverAddress });
             }
             catch
             {
                 return false;
             }
         }
     }
     else
         DisplayMessage("����" + serverAddress + "���ɹ�!");
     return true;
 }
 public void JoinMulticastGroup(System.Net.IPAddress multicastAddr)
 {
 }
Esempio n. 53
0
        static void Main(string[] args)
        {
            String[] src = File.ReadAllLines(@"C:\Users\ymine\skkdic\SKK-JISYO.L", Encoding.GetEncoding("EUC-JP"));
            if (src == null)
            {
                System.Environment.Exit(0);
            }
            List <String> dic = new List <string>(src);

            dic.Sort();
            List <String> midasi = new List <string>();

            foreach (String item in dic)
            {
                midasi.Add(item.Split(' ')[0]);
            }

            //ListenするIPアドレス
            string ipString = "127.0.0.1";

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

            //ホスト名からIPアドレスを取得する時は、次のようにする
            //string host = "localhost";
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.GetHostEntry(host).AddressList[0];
            //.NET Framework 1.1以前では、以下のようにする
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.Resolve(host).AddressList[0];

            //Listenするポート番号
            int port = 2001;

            //TcpListenerオブジェクトを作成する
            System.Net.Sockets.TcpListener listener =
                new System.Net.Sockets.TcpListener(ipAdd, port);

            //Listenを開始する
            listener.Start();
            Console.WriteLine("Listenを開始しました({0}:{1})。",
                              ((System.Net.IPEndPoint)listener.LocalEndpoint).Address,
                              ((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求があったら受け入れる
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("クライアント({0}:{1})と接続しました。",
                              ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
                              ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);

            //NetworkStreamを取得
            System.Net.Sockets.NetworkStream ns = client.GetStream();

            //読み取り、書き込みのタイムアウトを10秒にする
            //デフォルトはInfiniteで、タイムアウトしない
            //(.NET Framework 2.0以上が必要)
            // ns.ReadTimeout = 10000;
            // ns.WriteTimeout = 10000;

            //クライアントから送られたデータを受信する
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            bool disconnected        = false;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes           = new byte[256];
            int    resSize            = 0;

            /**
             * while ((resSize = ns.Read(resBytes, 0, resBytes.Length)) != 0)
             * {
             *  ms.Write(resBytes, 0, resSize);
             * }
             * */
            do
            {
                //データの一部を受信する
                resSize = ns.Read(resBytes, 0, resBytes.Length);
                //Readが0を返した時はクライアントが切断したと判断
                if (resSize == 0)
                {
                    disconnected = true;
                    Console.WriteLine("クライアントが切断しました。");
                    break;
                }
                //受信したデータを蓄積する
                ms.Write(resBytes, 0, resSize);
                //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                // 受信を続ける
            } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
            //受信したデータを文字列に変換
            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

            ms.Close();
            //末尾の\nを削除
            resMsg = resMsg.TrimEnd('\n');
            // resMsg = resMsg.TrimEnd('\r');
            Console.WriteLine(resMsg);
            int    index   = midasi.BinarySearch(resMsg);
            String sendMsg = String.Empty;

            if (index > -1)
            {
                sendMsg = dic[index].Split(' ')[1];
            }
            else
            {
                sendMsg = "Not found...";
            }
            //クライアントにデータを送信する
            //クライアントに送信する文字列を作成
            //文字列をByte型配列に変換
            byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
            //データを送信する
            ns.Write(sendBytes, 0, sendBytes.Length);
            Console.WriteLine(sendMsg);

            //閉じる
            ns.Close();
            client.Close();
            Console.WriteLine("クライアントとの接続を閉じました。");

            //リスナを閉じる
            listener.Stop();
            Console.WriteLine("Listenerを閉じました。");

            Console.ReadLine();
        }
Esempio n. 54
0
 //When start button is pressed
 private void StartButton_Click(object sender, EventArgs e)
 {
     System.Net.IPAddress ip = System.Net.IPAddress.Parse(textHost.Text);
     server.Start(ip, Convert.ToInt32(textPort.Text));
     StatusText.Text += "Server started.\r\n";
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="message"></param>
 /// <param name="ip"></param>
 /// <param name="port"></param>
 /// <param name="netClass"></param>
 /// <param name="Sock"></param>
 public DataArrivalEventArgs( Msg message, System.Net.IPAddress ip, int port,NatClass netClass,object Sock)
 {
     this.msg = message;
     this.IP = ip;
     this.Port = port;
     this.NetClass = netClass;
     this.SockObj = Sock;
 }
Esempio n. 56
0
 public static bool IsLoopback(System.Net.IPAddress address)
 {
     throw null;
 }
 /// <summary>
 /// <param name="data">接收到的数据字节数组</param>
 /// <param name="ip">发送数据方的IP地址</param>
 /// <param name="port">发送数据方的端口号</param>
 /// </summary>
 public DataArrivalEventArgs(byte[] data, System.Net.IPAddress ip, int port)
 {
     this.Data = data;
     this.IP = ip;
     this.Port = port;
 }
Esempio n. 58
0
 public static bool TryParse(string ipString, out System.Net.IPAddress address)
 {
     throw null;
 }
Esempio n. 59
0
        public static void Open( string filename )
        {
            if ( Playing )
                return;

            btnPlay.Enabled = btnStop.Enabled = false;
            if ( m_GZIn != null )
                m_GZIn.Close();
            try
            {
                m_GZIn = new GZBlockIn( filename );//new BinaryReader( new FileStream( filename, FileMode.Open, FileAccess.Read, FileShare.Read ) );

                m_Version = m_GZIn.Raw.ReadByte();

                if ( m_Version > PlayerVersion )
                {
                    m_GZIn.Close();
                    m_GZIn = null;
                    MessageBox.Show( Engine.MainWindow, Language.GetString( LocString.WrongVer ), "Version Mismatch", MessageBoxButtons.OK, MessageBoxIcon.Stop );
                    return;
                }

                m_GZIn.IsCompressed = m_Version > 1;

                byte[] filehash = m_GZIn.Raw.ReadBytes( 16 );
                DateTime created = DateTime.FromFileTime( m_GZIn.Raw.ReadInt64() );
                TimeSpan len = TimeSpan.FromMilliseconds( m_GZIn.Raw.ReadInt32() );

                string player = m_GZIn.Compressed.ReadString();
                string shard = m_GZIn.Compressed.ReadString();
                System.Net.IPAddress ip = System.Net.IPAddress.Any;
                try
                {
                    if ( m_Version > 1 )
                        ip = new System.Net.IPAddress( (long)m_GZIn.Compressed.ReadUInt32() );
                }
                catch
                {
                }

                m_StartPos = (int)m_GZIn.Position;

                long rawPos = m_GZIn.RawStream.Position;
                m_GZIn.RawStream.Seek( 1+16, SeekOrigin.Begin );
                using ( MD5 md5 = MD5.Create() )
                {
                    byte[] check = md5.ComputeHash( m_GZIn.RawStream );
                    for(int i=0;i<check.Length;i++)
                    {
                        if ( check[i] != filehash[i] )
                        {
                            m_GZIn.Close();
                            m_GZIn = null;
                            MessageBox.Show( Engine.MainWindow, Language.GetString( LocString.VideoCorrupt ), "Damaged File", MessageBoxButtons.OK, MessageBoxIcon.Error );
                            return;
                        }
                    }
                }
                m_GZIn.RawStream.Seek( rawPos, SeekOrigin.Begin );

                m_CurLength = len;
                m_Elapsed = TimeSpan.Zero;

                UpdateTimeText();

                m_RPVInfo = lblPlay.Text = String.Format( "File: {0}\nLength: {1} ({2})\nDate: {3}\nRecorded by \"{4}\" on \"{5}\" ({6})\n", Path.GetFileName( filename ), Utility.FormatTime( (int)len.TotalSeconds ), Utility.FormatSize( m_GZIn.RawStream.Length ), created.ToString( "M-dd-yy @ h:mmtt" ), player, shard, ip );
                btnClose.Enabled = btnPlay.Enabled = btnStop.Enabled = true;
                tbPos.Maximum = (int)len.TotalSeconds;
                tbPos.Minimum = 0;
            }
            catch ( Exception e )
            {
                if ( e is FileNotFoundException )
                {
                    MessageBox.Show( Engine.MainWindow, e.Message, "File not found.", MessageBoxButtons.OK, MessageBoxIcon.Error );
                }
                else
                {
                    Engine.LogCrash( e );
                    MessageBox.Show( Engine.MainWindow, Language.GetString( LocString.ReadError ), "Read Error", MessageBoxButtons.OK, MessageBoxIcon.Error );
                }
                m_GZIn.Close();
                m_GZIn = null;
                return;
            }
        }
Esempio n. 60
0
 public static bool TryParse(ReadOnlySpan <char> ipString, out System.Net.IPAddress address)
 {
     throw null;
 }