Exemple #1
0
        public bool CheckHost(string emailAdrress) //true = are erori - pt. angular validation
        {
            try
            {
                string      hostname = emailAdrress.Split('@')[1];
                IPHostEntry IPhst    = Dns.GetHostEntry(hostname);

                /*
                 * IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
                 * Socket s = new Socket(endPt.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                 * s.Connect(endPt);
                 */
                if (IPhst == null || IPhst.AddressList.Length == 0)
                {
                    return(false);
                }
            }catch (Exception exp)
            {
                LogWriter.Log(exp);
                return(false);
            }
            try
            {
                string      hostname = emailAdrress.Split('@')[1];
                IPHostEntry IPhst    = Dns.GetHostByName(hostname);
                if (IPhst == null || IPhst.AddressList.Length == 0)
                {
                    return(false);
                }
            }
            catch (Exception exp)
            {
                LogWriter.Log(exp);
                return(false);
            }
            return(true);
        }
Exemple #2
0
        public static void TaskStarted(TaskBase task)
        {
            bool ActiveThreadCountIncremented = false;

            try
            {
                task.TaskRecordItem.ThreadID = Thread.CurrentThread.GetHashCode();
                if (task.TaskRecordItem.Status != true)
                {
                    task.TaskRecordItem.Status = false;
                }
                task.TaskRecordItem.ReturnText = "Process Started";

                IPHostEntry entries = Dns.GetHostByName(Dns.GetHostName());
                task.TaskRecordItem.Server = entries.AddressList[0].ToString();

                RemoveFromScheduleQueue(task.TaskRecordItem);
                AddToScheduleInProgress(task.TaskRecordItem);

                Interlocked.Increment(ref ActiveThreadCount);
                ActiveThreadCountIncremented = true;

                task.TaskRecordItem.HistoryStartDate  = DateTime.Now;
                task.TaskRecordItem.ScheduleHistoryID = SchedulerController.AddTaskHistory(task.TaskRecordItem);
            }
            catch (Exception exc)
            {
                if (ActiveThreadCountIncremented)
                {
                    Interlocked.Decrement(ref ActiveThreadCount);
                }
                if (task.TaskRecordItem != null)
                {
                    ErrorLogger.SchedulerProcessException(exc);
                }
            }
        }
        public void BindAddress(int port)
        {
            Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            tmp.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
            //tmp.Bind(new IPEndPoint(IPAddress.Parse(this.local), port));
            //bindedSockets.Add(tmp);

            // Get host name
            String strHostName = Dns.GetHostName();

            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

            // Enumerate IP addresses
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                Socket tmp2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                tmp2.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
                tmp2.Bind(new IPEndPoint(ipaddress, port));

                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                byte[] buffer          = new byte[1024];
                e.SetBuffer(buffer, 0, buffer.Length);

                e.Completed += (sender, e2) =>
                {
                    Console.WriteLine(" Received" + e2.ReceiveMessageFromPacketInfo.Address + " from " + ipaddress.ToString());
                };

                tmp2.ReceiveAsync(e);

                bindedSockets.Add(tmp2);
            }

            bindedSockets.Add(tmp);
        }
        private static List <Book> InitBooks()
        {
            string MyIpStatic;
            string hostName = Dns.GetHostName(); // Retrive the Name of HOST

            string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();

            //string myIP1; // = Dns.GetHostByName(hostName).AddressList[1].ToString();

            if (myIP == "")
            {
                MyIpStatic = Dns.GetHostByName(hostName).AddressList[1].ToString();;
            }
            else
            {
                MyIpStatic = myIP;
            }


            var booklist = new List <Book>();

            booklist.Add(new Book
            {
                Id           = 1,
                Title        = "PT Gunung Madu Plantations",
                Author       = "IT-GMP@2019",
                COM_SET      = SerialConnection._portSetting,
                COM_STATUS   = SerialConnection.portStatus,
                COM_MESSAGE  = SerialConnection._PortMessage,
                VALUE        = SerialConnection._Value,
                DATA_LOG     = SerialConnection._dataLog,
                HostName     = hostName,
                LocalAddress = MyIpStatic
            });

            return(booklist);
        }
Exemple #5
0
        public void Init()
        {
            loginAuth.LostFocus += LoginAuth_LostFocus;
            loginAuth.GotFocus  += LoginAuth_GotFocus;
            passAuth.LostFocus  += PassAuth_LostFocus;
            passAuth.GotFocus   += PassAuth_GotFocus;


            Message mess = new Message();

            mess.Add(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString());
            request  = JsonConvert.SerializeObject(mess);
            response = server.SendMsg("GetAuth", "", request);
            message  = JsonConvert.DeserializeObject <Message>(response);
            try
            {
                addres = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\server.conf");
            }
            catch { }
            try
            {
                if (message.args[0] != "no")
                {
                    Data.Security    = message.args[1];
                    Data.NameUser    = message.args[0];
                    Data.ProjectName = message.args[3];
                    Data.ServiceName = message.args[2];
                    Data.IPServer    = addres;
                    Data.Stend       = message.args[4];

                    mainWindow.Show();

                    this.Close();
                }
            }
            catch { }
        }
Exemple #6
0
        private void Form1_Load(object sender, EventArgs e)
        {
            // Получение имени компьютера.
            String host = System.Net.Dns.GetHostName();

            // Получение ip-адреса.
            CurrentIP = Dns.GetHostByName(host).AddressList[0];

            //server = new Server(this,address:CurrentIP.ToString());
            toolStripStatusLabel1.Text = "Режим : Сервер";
            //client = new Client(this);
            //toolStripStatusLabel3.Text = "Save dir: " + Directory.GetCurrentDirectory() + @"\";

            /*try
             * {
             *  cFile = Serializer.DeserializeFromFile();
             *  if (cFile.filePointer >= cFile.Length)
             *  {
             *      Serializer.Clean();
             *      cFile = null;
             *  }
             *  userFileControl1.StartBtn.BeginInvoke(new MethodInvoker(delegate ()
             *  {
             *      if (cFile != null)
             *      {
             *          userFileControl1.progressBar1.Value = (int)Math.Ceiling((double)cFile.filePointer / (double)cFile.Length * 100);
             *          tbFileDatas.Text += cFile.ToString();
             *          userFileControl1.StartBtn.Text = "Resume";
             *          userFileControl1.StartBtn.Click -= new EventHandler(this.SendFile_Click);
             *          userFileControl1.StartBtn.Click += new EventHandler(this.ResumeFile);
             *          ShowServerMessage("File is ready...");
             *      }
             *  }));
             * }
             * catch (Exception ex) { }*/
            UpdateStatus(server);
        }
Exemple #7
0
        public void MakeRequest(string commandName, string[] args, IGlobalCommand command, Commands.Attributes.Command attribute)
        {
            var template = attribute.Template;
            var body     = command.Send(args);
            var targets  = command.GetTargets(args);

            string hostName = Dns.GetHostName(); // Retrive the Name of HOST
            var    ips      = Dns.GetHostByName(hostName).AddressList;
            string ip       = ips[ips.Length - 1].ToString();

            foreach (var target in targets)
            {
                var socket = client.StartSocket(target.Item1, target.Item2);

                if (!AsyncClient.CanConnect)
                {
                    Console.WriteLine($"Cannot connect to {target.Item1}:{target.Item2}");
                    continue;
                }

                var data = new SocketDataBody()
                {
                    CommandName = commandName,
                    Body        = body,
                    Type        = SocketDataType.Send,
                    NodesPair   = new Tuple <string, string>($"{ip}:{AsyncListener.Port}", $"{target.Item1.ToString()}:{target.Item2}")
                };

                client.Send(socket, data);
                AsyncClient.sendDone.WaitOne();

                client.Receive(socket);
                AsyncClient.receiveDone.WaitOne();

                //client.StopSocket(socket);
            }
        }
        protected void btn_save_Click(object sender, EventArgs e)
        {
            int dr1 = 0;

            foreach (GridViewRow item in grid_display.Rows)
            {
                string call_id1 = item.Cells[0].Text.ToString();
                int    call_id  = Convert.ToInt32(call_id1);

                DropDownList callStat = (DropDownList)item.FindControl("callStat");
                string       status   = callStat.SelectedValue.ToString();

                string hostName = Dns.GetHostName(); // Retrive the Name of HOST
                // Get the IP
                string      myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
                TextBox     dt   = (TextBox)item.FindControl("txt_date");
                string      dt1  = Convert.ToDateTime(dt.Text).ToString("yyyy/MM/dd");
                OdbcCommand cmd  = conn_asset.CreateCommand();
                cmd.CommandText = "update ast_call set callStat = '" + status + "' , draftDate = '" + dt1 + "', droppingIP = '" + myIP.Trim() + "',droppedBy = '" + userID.Trim() + "' where call_id = '" + call_id + "'";
                conn_asset.Open();
                dr1 = cmd.ExecuteNonQuery();
                conn_asset.Close();
                BindData();
            }
            if (dr1 == 1)
            {
                lbl_error.ForeColor = System.Drawing.Color.Green;
                lbl_error.Text      = "Success";
                lbl_error.Visible   = true;
            }
            else
            {
                lbl_error.ForeColor = System.Drawing.Color.Red;
                lbl_error.Text      = "Failed";
                lbl_error.Visible   = true;
            }
        }
Exemple #9
0
        static void ServerInit()
        {
            /*
             * Windows needs firewall hole
             * Inbound rules and outbound rules need TCP 5000 port open from anywhere
             */
            Console.WriteLine("-------Starting server-------");
            _httpListener.Prefixes.Add("http://localhost:5000/");
            _httpListener.Prefixes.Add("http://127.0.0.1:5000/");
            //_httpListener.Prefixes.Add("http://10.103.1.200:5000/"); // tämä on koneen oma ip joka haettiin cmd ja ipconfig

            Console.WriteLine("Adding IP adresses to list:");

            //https://stackoverflow.com/questions/5271724/get-all-ip-addresses-on-machine
            // Get host name
            String strHostName = Dns.GetHostName();
            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

            // Enumerate IP addresses
            foreach (IPAddress ip in iphostentry.AddressList)
            {
                Console.WriteLine("http://" + ip.ToString() + ":5000/");
                _httpListener.Prefixes.Add("http://" + ip.ToString() + ":5000/");
            }

            _httpListener.Start(); // start server (Run application as Administrator!)
            Console.WriteLine("-------Server started-------");

            //esimerkki json
            Thread _responseThread = new Thread(JsonPack);

            //esimerkki 1
            //Thread _responseThread = new Thread(ResponseThread);

            _responseThread.Start(); // start the response thread
        }
Exemple #10
0
        // ロード時の処理(コンボボックスに、オートコンプリート機能の追加)
        private void Form5_Load(object sender, EventArgs e)
        {
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
            {
                Version deploy = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;

                StringBuilder version = new StringBuilder();
                version.Append("VERSION: ");
                //version.Append(applicationName + "_");
                version.Append(deploy.Major);
                version.Append("_");
                //version.Append(deploy.Minor);
                //version.Append("_");
                version.Append(deploy.Build);
                version.Append("_");
                version.Append(deploy.Revision);

                Version_lbl.Text = version.ToString();
            }

            txtPwd.Visible       = false;
            btnLogIn.Enabled     = false;
            grChangePass.Visible = false;
            string sql = "select DISTINCT qcuser FROM qc_user ORDER BY qcuser";
            TfSQL  tf  = new TfSQL();

            tf.getComboBoxData(sql, ref cmbUserName);
            tf.getComboBoxData(sql, ref cmbUserC);

            string      HostName = Dns.GetHostName();
            IPHostEntry ip       = Dns.GetHostByName(HostName);

            foreach (IPAddress ipadd in ip.AddressList)
            {
                lblIP.Text = lblIP.Text + ipadd.ToString();
            }
        }
Exemple #11
0
        // 添加好友方法
        private void AddFriend_Click(object sender, EventArgs e)
        {
            // 向255.255.255.255发送消息
            // 设置Socket类型
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            // 设置Socket等级
            s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            // 设置要发送的IP
            IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 23333);

            // 最终用来传输的集合
            List <byte> list = new List <byte>();
            byte        b    = 0;

            list.Add(b);

            // 获取本机IP地址
            IPAddress ipaddress = Dns.GetHostByName(Dns.GetHostName()).AddressList[0];
            string    strIp     = ipaddress.ToString();

            //使用Json来序列化自己的信息
            Friend f = new Friend();

            f.IP        = strIp;
            f.Name      = this.MyName;
            f.Photo     = this.MyPhoto;
            f.Signature = this.Signature;
            JavaScriptSerializer js = new JavaScriptSerializer();
            string strF             = js.Serialize(f);

            list.AddRange(Encoding.UTF8.GetBytes(strF));

            // 进行发送  协议0+本机ip
            s.SendTo(list.ToArray(), ip);
            s.Close();
        }
Exemple #12
0
        public MainWindow()
        {
            InitializeComponent();
            // Set up handler for key press events
            this.KeyDown += new KeyEventHandler(Main_KeyDown);

            // Initialize logging
            initLog();

            eyeXHost = new EyeXHost();
            eyeXHost.Start();
            var gazeData = eyeXHost.CreateGazePointDataStream(GazePointDataMode.LightlyFiltered);

            gazeData.Next += gazePoint;

            lineSetup();

            if (ReceiverOn)
            {
                IPHostEntry ipHostInfo = Dns.GetHostByName(Dns.GetHostName());
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                //Receive_Status_Text.Text = "Receiving Data at\nIP:" + ipAddress.ToString();
                //Receive_Status_Text.Visibility = Visibility.Visible;
            }
            if (SenderOn)
            {
                SenderIP = defaultSenderIP;
                //Share_Status_Text.Text = "Sharing Data to\nIP:" + SenderIP.ToString();
                //Share_Status_Text.Visibility = Visibility.Visible;
                communication_started_Sender = false;
            }

            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer(System.Windows.Threading.DispatcherPriority.Render);
            dispatcherTimer.Tick    += new EventHandler(update);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 10);
            dispatcherTimer.Start();
        }
        private void OpenControlConnection(ServicePoint svcPoint)
        {
            Socket   controlSocket    = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint clientIPEndPoint = new IPEndPoint(IPAddress.Any, 0);

            try
            {
                controlSocket.Bind(clientIPEndPoint);
                IPHostEntry serverHostEntry = Dns.GetHostByName(uri.Host);
                IPEndPoint  serverEndPoint  = new IPEndPoint(serverHostEntry.AddressList[0], uri.Port);                 // TODO: Rollback to try other addresses if first one fails...
                controlSocket.Connect(serverEndPoint);
                controlStream = new FtpControlStream(controlSocket);
            }
            catch (Exception)
            {
                controlSocket.Close();
                throw;
            }
            catch
            {
                controlSocket.Close();
                throw;
            }
        }
        public string GetIpFromDns(string dns)
        {
            StringBuilder result = new StringBuilder();

            result.AppendLine($"Adresses of {dns}:");



            foreach (var ip in Dns.GetHostAddresses(dns))
            {
                switch (ip.AddressFamily)
                {
                case AddressFamily.InterNetwork:
                    result.AppendLine($"IpV4: {ip}");
                    break;

                case AddressFamily.InterNetworkV6:
                    result.AppendLine($"IpV6: {ip}");
                    break;
                }
            }

            var host = Dns.GetHostByName(dns);

            result.AppendLine("Addresses of the dns: ");

            host.AddressList.ToList().ForEach(address => result.AppendLine($"{address.ToString()}"));

            result.Append("Aliases of dns: ");

            host.Aliases
            .ToList()
            .ForEach(alias => result.Append($"{alias}, "));

            return(result.ToString());
        }
Exemple #15
0
        async void myIP()
        {
            try
            {
                string MyHost = Dns.GetHostName();
                foreach (var dd in Dns.GetHostByName(MyHost).AddressList)
                {
                    string tip = "IP4";
                    if (dd.AddressFamily.ToString().Contains("6"))
                    {
                        tip = "IP6";
                    }
                    if (tip == "IP4")
                    {
                        // St.Text = dd.ToString().Split(".")[0] + "." + dd.ToString().Split(".")[1] + "." + dd.ToString().Split(".")[2] + "." + "1";
                        //  En.Text = dd.ToString().Split(".")[0] + "." + dd.ToString().Split(".")[1] + "." + dd.ToString().Split(".")[2] + "." + "255";
                    }
                }
                var f = from d in viewIP.ListMyIP where d.Activ == true select d.MyIp4;
                if (f.Count() == 1)
                {
                    St.Text = f.ElementAt(1).ToString().Split(".")[0] + "." + f.ElementAt(1).ToString().Split(".")[1] + "." + f.ElementAt(1).ToString().Split(".")[2] + "." + "1";
                    En.Text = f.ElementAt(1).ToString().Split(".")[0] + "." + f.ElementAt(1).ToString().Split(".")[1] + "." + f.ElementAt(1).ToString().Split(".")[2] + "." + "255";
                }
                if (f.Count() > 1)
                {
                    St.Text = f.ElementAt(1).ToString().Split(".")[0] + "." + f.ElementAt(1).ToString().Split(".")[1] + "." + f.ElementAt(1).ToString().Split(".")[2] + "." + "1";
                    En.Text = f.ElementAt(1).ToString().Split(".")[0] + "." + f.ElementAt(1).ToString().Split(".")[1] + "." + f.ElementAt(1).ToString().Split(".")[2] + "." + "255";
                }

                App.ThemeManager.LoadTheme(ThemeManager.DarkThemePath);
            }
            catch (Exception ex)
            {
            }
        }
Exemple #16
0
        public static string Ip(string[] args)
        {
            string strHostName;
            string strHost = "";

            if (args.Length == 0)
            {
                strHostName = Dns.GetHostName();
            }
            else
            {
                strHostName = args[0];
            }

            IPHostEntry ipEntry = Dns.GetHostByName(strHostName);

            IPAddress[] addr = ipEntry.AddressList;
            for (int i = 0; i < addr.Length; i++)
            {
                Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
                strHost += addr[i].ToString();
            }
            return(addr[0].ToString());
        }
Exemple #17
0
        public static int GetLocalNum()
        {
            string Host       = Dns.GetHostName();
            int    localNum   = -1;
            var    adressList = Dns.GetHostByName(Host).AddressList;

            try
            {
                foreach (var adress in adressList)
                {
                    if (adress.ToString().Contains(Configs.Mask))
                    {
                        localNum = int.Parse(adress.ToString().Replace(Configs.Mask, ""));
                        break;
                    }
                }
            }
            catch (Exception)
            {
                localNum = -1;
            }

            return(localNum);
        }
Exemple #18
0
        static void Main(string[] args)
        {
            IPHostEntry iPHost = Dns.GetHostByName("localhost");

            IPAddress address = iPHost.AddressList[0];

            IPEndPoint endPoint = new IPEndPoint(address, 8080);

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            byte[] bytes = new byte[1024];

            try
            {
                socket.Bind(endPoint);
                socket.Listen(10);
                string data = null;

                while (true)
                {
                    Socket handler = socket.Accept();

                    int count = handler.Receive(bytes);

                    data = Encoding.ASCII.GetString(bytes, 0, count);
                    Console.WriteLine("Rob: " + data);

                    socket.Send(bytes);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            //Socket socket = new Socket()
        }
Exemple #19
0
        public bool IsResolvableEx(string host)
        {
            if (String.IsNullOrEmpty(host))
            {
                return(false);
            }
            IPHostEntry ipHostEntry = null;

            try
            {
                ipHostEntry = Dns.GetHostByName(host);
            }
            catch { }
            if (ipHostEntry == null)
            {
                return(false);
            }
            IPAddress[] addresses = ipHostEntry.AddressList;
            if (addresses.Length == 0)
            {
                return(false);
            }
            return(true);
        }
        void ListenForClients()
        {
            //Debug.Log("ListenForClients0");
            this.tcpListener.Start();
            string ip = ((IPEndPoint)tcpListener.LocalEndpoint).Address.ToString();
            //Debug.Log("ListenForClients1: "+ip);
            string      sHostName = Dns.GetHostName();
            IPHostEntry ipE       = Dns.GetHostByName(sHostName);

            IPAddress[] IpA = ipE.AddressList;
            for (int i = 0; i < IpA.Length; i++)
            {
                string path = IpA[i].ToString() + ":8888";
                string s    = String.Format("IP Address [{0}] {1} ", i, path);
                Console.WriteLine(s);
                pathes.Add(path);
            }

            while (isListening)
            {
                try
                {
                    //blocks until a client has connected to the server
                    TcpClient client = this.tcpListener.AcceptTcpClient();
                    Console.WriteLine("client connected!: #" + clients.Count);
                    ParameterizedThreadStart tStart = new ParameterizedThreadStart(HandleClientComm);
                    //Thread clientThread=new Thread(tStart);
                    //clientThread.Start(client);
                    HandleClientComm(client);
                    break;
                }
                catch (Exception e) {
                }
                //Debug.Log("client");
            }
        }
        private void start_button_Click(object sender, EventArgs e)
        {
            IPAddress IP;

            if (!IPAddress.TryParse(ip_textBox.Text, out IP))
            {
                throw new ArgumentException();
            }
            string host  = ip_textBox.Text;
            string my_ip = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString();

            if (admin_checkBox.Checked)
            {
                active_form = new ControllingForm(host, my_ip, this);
                active_form.Show();
                this.Hide();
            }
            else
            {
                UserForm user_form = new UserForm(host, my_ip, this);
                user_form.Show();
                Hide();
            }
        }
Exemple #22
0
 private void MaterialRaisedButton1_Click(object sender, EventArgs e)
 {
     try
     {
         host = Dns.GetHostName();
         WebClient client = new WebClient();
         ip = client.DownloadString("https://icanhazip.com/");
         materialSingleLineTextField1.Text = host;
         materialSingleLineTextField2.Text = ip;
         materialSingleLineTextField3.Text = Dns.GetHostByName(host).AddressList[0].ToString();
         materialLabel5.Text = GeoInfo(ip);
         ip = null;
         pictureBox1.Visible = false;
         pictureBox2.Visible = false;
         pictureBox3.Visible = false;
         ip = null;
     }
     catch
     {
         pictureBox1.Visible = true;
         pictureBox2.Visible = true;
         pictureBox3.Visible = true;
     }
 }
Exemple #23
0
        public void Connect(string ipAddress, int Port)
        {
            if (_client != null && _client.Connected)
            {
                _client.Shutdown(SocketShutdown.Both);
                Thread.Sleep(10);
                _client.Close();
            }
            string      strHostName = Dns.GetHostName();
            IPHostEntry entry       = Dns.GetHostByName("192.168.0.1");

            IPAddress[] aryLocalAddr = entry.AddressList;
            if (aryLocalAddr == null || aryLocalAddr.Length < 1)
            {
                throw new Exception("Cannot obtain the local address");
            }

            _client          = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _epServer        = new IPEndPoint(aryLocalAddr[0], 5000);
            _client.Blocking = false;
            AsyncCallback onconnect = new AsyncCallback(OnConnect);

            _client.BeginConnect(_epServer, onconnect, _client);
        }
Exemple #24
0
        public ArrayList GetLocalIPByArp()
        {
            Process p = new Process();

            p.StartInfo.FileName               = "cmd.exe";
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardInput  = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            p.StartInfo.CreateNoWindow         = true;
            p.Start();
            p.StandardInput.WriteLine("arp -a");
            p.StandardInput.WriteLine("exit");
            ArrayList    list   = new ArrayList();
            StreamReader reader = p.StandardOutput;
            string       IPHead = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString().Substring(0, 3);

            for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
            {
                line = line.Trim();
                if (line.StartsWith(IPHead) && (line.IndexOf("dynamic") != -1))
                {
                    string       IP           = line.Substring(0, 15).Trim();
                    string       Mac          = line.Substring(line.IndexOf("-") - 2, 0x11).Trim();
                    LocalMachine localMachine = new LocalMachine();
                    localMachine.MachineIP   = IP;
                    localMachine.MachineMAC  = Mac;
                    localMachine.MachineName = "";
                    list.Add(localMachine);

                    richTextBoxLog.Text += "" + IP + "  成功\r\n";
                    // SetRemote(IP);
                }
            }
            return(list);
        }
Exemple #25
0
        /// <summary>
        /// 获取MAC地址
        /// </summary>
        /// <returns></returns>
        public static string GetMac()
        {
            StringBuilder strReturn = new StringBuilder();

            try
            {
                System.Net.IPHostEntry Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(Dns.GetHostName());
                System.Net.IPAddress[] TempAd   = Tempaddr.AddressList;
                Int32 remote  = (int)TempAd[0].Address;
                Int64 macinfo = new Int64();
                Int32 length  = 6;
                SendARP(remote, 0, ref macinfo, ref length);

                string temp = System.Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();

                int x = 12;
                for (int i = 0; i < 6; i++)
                {
                    if (i == 5)
                    {
                        strReturn.Append(temp.Substring(x - 2, 2));
                    }
                    else
                    {
                        strReturn.Append(temp.Substring(x - 2, 2) + "-");
                    }
                    x -= 2;
                }

                return(strReturn.ToString());
            }
            catch
            {
                return("");
            }
        }
Exemple #26
0
        /// <summary>
        /// 获取服务器IP
        /// </summary>
        /// <returns></returns>
        public static string GetServiceIP()
        {
            string ip = "";

            try
            {
                System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;

                if (addressList.Length >= 1)
                {
                    return(Converter.ParseString(addressList[0], ""));
                }
                else
                {
                    return(Converter.ParseString(addressList.Length, "0"));
                }
            }
            catch (Exception)
            {
                ip = "获取服务器IP异常";
            }

            return(ip);
        }
        static void Main(string[] args)
        {
            String strHostName = string.Empty;

            if (args.Length == 0)
            {
                /* First get the host name of local machine.*/
                strHostName = Dns.GetHostName();
                Console.WriteLine("Local Machine's Host Name: " + strHostName);
            }
            else
            {
                strHostName = args[0];
            }
            /* Then using host name, get the IP address list..*/
            IPHostEntry ipEntry = Dns.GetHostByName(strHostName);

            IPAddress[] addr = ipEntry.AddressList;
            for (int i = 0; i < addr.Length; i++)
            {
                Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
            }
            Console.ReadLine();
        }
Exemple #28
0
        public frmTelnet()
        {
            // Build the form
            InitializeComponent();

            // Restore the users settings
            InitializeControlValues();

            // Enable/disable controls based on the current state
            EnableControls();

            IPAddress[] AddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;

            string ip = AddressList[0].ToString();

            if (ip != "")
            {
                this.sbpLocIP.Text = "本地IP地址:" + ip;
            }
            else
            {
                this.sbpStatus.Text = "无法获得本机IP地址,请检查网络连接";
            }
        }
Exemple #29
0
        private void button1_Click(object sender, EventArgs e)
        {
            string hostName = Dns.GetHostName();
            string myIP     = Dns.GetHostByName(hostName).AddressList[0].ToString();

            label3.Text = hostName + "/ IP /" + myIP;
            //textBox1.Text = myIP;
            //label4.Text = "Error " + " Can not make session";
            IPHostEntry host      = Dns.GetHostEntry(Dns.GetHostName());
            string      IPAddress = string.Empty;

            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    IPAddress    = ip.ToString();
                    label4.Text += IPAddress + "\n";
                    break;
                }
            }
            //Console.WriteLine(IPAddress);
            //Console.ReadKey();
            textBox1.Text = IPAddress;
        }
Exemple #30
0
        public static void Main()
        {
            IPAddress test1 = IPAddress.Parse("192.168.1.1");
            IPAddress test2 = IPAddress.Loopback;
            IPAddress test3 = IPAddress.Broadcast;
            IPAddress test4 = IPAddress.Any;
            IPAddress test5 = IPAddress.None;

            IPHostEntry ihe    = Dns.GetHostByName(Dns.GetHostName());
            IPAddress   myself = ihe.AddressList[0];

            if (IPAddress.IsLoopback(test2))
            {
                Console.WriteLine("The Loopback address is: {0}", test2.ToString());
            }
            else
            {
                Console.WriteLine("Error obtaining the loopback address");
            }

            Console.WriteLine("The Local IP address is: {0}\n", myself.ToString());

            if (myself == test2)
            {
                Console.WriteLine("The loopback address is the same as local address.\n");
            }
            else
            {
                Console.WriteLine("The loopback address is not the local address.\n");
            }

            Console.WriteLine("The test address is: {0}", test1.ToString());
            Console.WriteLine("Broadcast address: {0}", test3.ToString());
            Console.WriteLine("The ANY address is: {0}", test4.ToString());
            Console.WriteLine("The NONE address is: {0}", test5.ToString());
        }