Пример #1
0
        public static string GetPublicIP()
        {
            //外网(公网)IP
            Stream       stream       = null;
            StreamReader streamReader = null;
            IPAddress    PublicIP;

            try
            {
                stream       = WebRequest.Create("https://www.ipip5.com/").GetResponse().GetResponseStream();
                streamReader = new StreamReader(stream, Encoding.UTF8);
                var str   = streamReader.ReadToEnd();
                int first = str.IndexOf("<span class=\"c-ip\">") + 19;
                int last  = str.IndexOf("</span>", first);
                var ip    = str.Substring(first, last - first);
                PublicIP = IPAddress.Parse(ip);       //这里就得到了
            }
            catch (Exception ex)
            {
                throw new WxPayException($"出错了,{ex.Message}。获取失败");
            }
            finally
            {
                streamReader?.Dispose();
                stream?.Dispose();
            }

            return(PublicIP.ToString());
        }
Пример #2
0
        static void Main(string[] args)
        {
            string Date1      = DateTime.UtcNow.ToString("dddd, dd MMMM yyyy UTC HH;mm;ss ");
            string pathString = @"C:\Program Files (x86)\VAPOR Client\Logs";
            string fileName   = Date1 + "logs.csv";

            Directory.CreateDirectory(pathString);
            pathString = System.IO.Path.Combine(pathString, fileName);



            // Get host name
            string strHostName     = Dns.GetHostName();
            string WinComputerName = System.Environment.MachineName.ToString();

            // Get PC Uptime from Uptime class.
            System.TimeSpan Uptime = Uptimes.GetUptime();

            // Get Public IP from PublicIP class.
            string publicIP = PublicIP.getPublicIP();


            foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                string Date   = DateTime.UtcNow.ToString("dddd, dd MMMM yyyy");
                string PCName = WinComputerName.ToLower();

                if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (UnicastIPAddressInformation ip in netInterface.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            if (!System.IO.File.Exists(pathString))
                            {
                                Console.WriteLine("Creating file");
                                System.IO.FileStream fs = System.IO.File.Create(pathString);
                                fs.Close();
                                {
                                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(pathString))
                                    {
                                        file.WriteLine(Date + "," + ip.Address.ToString() + "," + netInterface.GetPhysicalAddress().ToString() + "," + WinComputerName + "," + strHostName + "," + HardDrive.GetHardDriveInfo().TrimStart() + "," + new ComputerInfo().OSFullName + "," + Uptime);
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("File \"{0}\" already exists, appending file", fileName);
                                using (System.IO.StreamWriter file = new System.IO.StreamWriter(pathString, true))
                                {
                                    file.WriteLine(Date + "," + ip.Address.ToString() + "," + netInterface.GetPhysicalAddress().ToString() + "," + WinComputerName + "," + strHostName + "," + HardDrive.GetHardDriveInfo().TrimStart() + "," + new ComputerInfo().OSFullName + "," + Uptime);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #3
0
        private void BuildMPGamesList(WebRequest.MPGamesList mpGamesList)
        {
            scrollContent.sizeDelta = new Vector2(scrollContent.sizeDelta.x, mpGamesList.mpGames.Length * (gameListEntryPrefab.GetComponent <RectTransform>().sizeDelta.y + scrollContent.GetComponent <VerticalLayoutGroup>().spacing));
            foreach (WebRequest.MPGame game in mpGamesList.mpGames)
            {
                GameObject go = Instantiate(gameListEntryPrefab, scrollContent);
                go.name = "MPGameEntry<" + game.name + ">";

                MPGameEntry ge = go.GetComponent <MPGameEntry>().Init(int.Parse(portInput.text), game.name);
                ge.JoinBtn.interactable = !hostPanel.Hosting;
                ge.JoinBtn.onClick.RemoveAllListeners();
                ge.JoinBtn.onClick.AddListener(() => {
                    SetLockAllButtons(true);

                    Info("Obtaining public IP...");
                    PublicIP.Fetch(this, (ip) => {
                        if (ip == null)
                        {
                            SetLockAllButtons(false);
                            Error("Could not obtain public IP address");
                        }
                        else
                        {
                            Info("Joining the game...");
                            WebRequest.Get(this, Global.WebRequestURLs.JOIN_MPGAME, (req, res, error, errorMsg) => {
                                if (error)
                                {
                                    SetLockAllButtons(false);
                                    Error("Could not join the game:\n" + errorMsg);
                                }
                                else
                                {
                                    WebRequest.MPGame mpGame;
                                    try { mpGame = JsonUtility.FromJson <WebRequest.MPGame>(res); } catch { Error("Could not parse game infos"); return; }
                                    Info("Connecting to host...");

                                    P2PManager.Inst.InitHost(ge.OwnPort);
                                    P2PManager.Inst.OnPeerConnect += (peer) => {
                                        Info("Connected. Starting game...");
                                        Global.State.playerTag = PlayerTag.Player1;
                                        SceneManager.LoadScene(Global.SceneNames.GAME_SCENE, LoadSceneMode.Single);
                                    };
                                    P2PManager.Inst.OnPeerException += (peer, exception) => {
                                        Error("Could not connect to host:\n" + exception.Message);
                                    };
                                    P2PManager.Inst.Connect(mpGame.hostIP, mpGame.hostPort);
                                }
                            }, new WebRequest.GetParam[] {
                                new WebRequest.GetParam("name", ge.GameName),
                                new WebRequest.GetParam("ownIP", ip.ToString()),
                                new WebRequest.GetParam("ownPort", ge.OwnPort.ToString())
                            });
                        }
                    });
                });
            }
        }
Пример #4
0
        /// <summary>
        /// Timer Action
        /// </summary>
        protected override void TimerAction()
        {
            Console.WriteLine(DateTime.Now + " : ");
            string    pub_ip = GetPublicIP();
            string    mac_nm = System.Environment.MachineName;
            string    usr_nm = System.Environment.UserName;
            IPAddress PublicIP;

            if (IPAddress.TryParse(pub_ip, out PublicIP))
            {
                Console.WriteLine("\tPC:" + mac_nm);
                Console.WriteLine("\tUR:" + usr_nm);
                Console.WriteLine("\tIP:" + PublicIP.ToString());
            }
        }
Пример #5
0
        /// <summary>
        /// Start The server and Setup initial variables and connections
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmServer_Load(object sender, EventArgs e)
        {
            // Get Azure Server Name, Table Name, User name and Password

            FrmAzureDatabaseLogin AzureLogin = new FrmAzureDatabaseLogin();
            DialogResult          dr         = AzureLogin.ShowDialog();

            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                AzureDB.SQLInfoMessage  += AzureDB_SQLInfoMessage;  // Get any messages from the SQL Database
                AzureDB.SQLStateChanged += AzureDB_SQLStateChanged; // Keep track of Database Connection Changes

                AzureDB.ConnectionString = "Server=tcp:" + AzureLogin.ServerName + ";Database=ChatApp;User ID=" + AzureLogin.UserName + ";Password="******";Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
                if (AzureDB.Connect())
                {
                    // Display our Public IP Address and the port we are listening to.
                    pip = new PublicIP();
                    pip.PublicIPKnown += pip_PublicIPKnown; // Get's the Public IP Address of the Server (Event)
                    pip.PublicIPError += pip_PublicIPError; // Notifies us of any Errors Getting the Public IP
                    pip.GetPublicIpAddress();               // Will Raise the above event
                    lblPort.Text = OurPort.ToString();

                    // Subscribe to Server Events
                    server.ConnectionClosed += server_ConnectionClosed;
                    server.DataReceived     += server_DataReceived;
                    server.DataTransferred  += server_DataTransferred;
                    server.errEncounter     += server_errEncounter;
                    server.lostConnection   += server_lostConnection;
                    server.onConnection     += server_onConnection;
                    server.StartConnection(); // Don't forget to start your server !!

                    // Now get total number of Registered Users.
                    TotalRegisteredUsers = AzureDB.GetRegisteredUsers();
                    UpdateTotalRegisteredUsers(TotalRegisteredUsers);
                }
                else
                {
                    MessageBox.Show("Azure Database Error: " + AzureDB.LastError);
                    lblConnectionState.Image = ServerClientChat1._3.Properties.Resources.database_red;
                }
            }
            else
            {
                MessageBox.Show("The Server cannot run unless connected to the Server's Azure SQL Database \n\rClosing Application");
                this.Close();
            }
        }
Пример #6
0
        public T FindbyId(string IpAddress)
        {
            var publicIP = new PublicIP();

            using (DBClass = new MSSQLDatabase())
            {
                var cmd = DBClass.GetStoredProcedureCommand("APP_GET_PUBLIC_IP_BY_ID") as SqlCommand;
                DBClass.AddSimpleParameter(cmd, "@IpAddress", IpAddress);
                var reader = DBClass.ExecuteReader(cmd);
                while (reader.Read())
                {
                    publicIP.PublicIPID = int.Parse(reader[0].ToString());
                    publicIP.IPAddress  = reader[1].ToString();
                }
            }
            return(publicIP as T);
        }
Пример #7
0
        public IEnumerable <T> FindAll(List <Dictionary <string, object> > keyValueParam)
        {
            var result = new List <PublicIP>();

            using (DBClass = new MSSQLDatabase())
            {
                var cmd = DBClass.GetStoredProcedureCommand("APP_GET_ALL_PUBLIC_IP") as SqlCommand;
                RoutinesParameterSetter.Set(ref cmd, keyValueParam);
                var reader = DBClass.ExecuteReader(cmd);
                while (reader.Read())
                {
                    var publicIP = new PublicIP();
                    publicIP.PublicIPID = int.Parse(reader[0].ToString());
                    publicIP.IPAddress  = reader[1].ToString();
                    result.Add(publicIP);
                }
            }
            return(result as List <T>);
        }
Пример #8
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            INatDevice device = args.Device;

            PublicIP.Invoke(new Action(() => PublicIP.Text = device.GetExternalIP().ToString()));

            if (isStarted == true)
            {
                if (portEnabled.Value == true)
                {
                    device.GetSpecificMapping(Protocol.Tcp, Convert.ToInt32(portTxt.Text));

                    device.CreatePortMap(new Mapping(Protocol.Tcp, Convert.ToInt32(portTxt.Text), Convert.ToInt32(portTxt.Text)));
                }
                else
                {
                    device.GetSpecificMapping(Protocol.Tcp, 10578);

                    device.CreatePortMap(new Mapping(Protocol.Tcp, 10578, 10578));
                }
            }
        }
Пример #9
0
        private void HostGame()
        {
            joinPanel.SetLockAllJoinButtons(true);
            hosting = true;
            token   = "";
            hostBtn.interactable   = false;
            nameInput.interactable = false;
            portInput.interactable = false;

            Info("Obtaining public IP...");
            PublicIP.Fetch(this, (ip) => {
                if (ip == null)
                {
                    Error("Could not obtain public IP address", true);
                }
                else
                {
                    Info("Connecting...");
                    WebRequest.Get(this, Global.WebRequestURLs.REGISTER_MPGAME, (req, res, error, errorMsg) => {
                        if (error)
                        {
                            Error("Unlucky, there was an error:\n" + errorMsg, true);
                        }
                        else
                        {
                            Application.wantsToQuit += ApplicationQuitHandler;
                            ListenForPlayerJoin(res);
                        }
                    }, new WebRequest.GetParam[] {
                        new WebRequest.GetParam("name", nameInput.text),
                        new WebRequest.GetParam("hostIP", ip.ToString()),
                        new WebRequest.GetParam("hostPort", portInput.text)
                    });
                }
            });
        }
Пример #10
0
 public void PublicIPWithValidAddress_ReturnsAddressAsInt()
 {
     Assert.AreEqual(3355508993, PublicIP.ToUInt32());
 }
Пример #11
0
 public void PublicIPWithValidAddress_ReturnsFalse()
 {
     Assert.IsFalse(PublicIP.IsPrivateAddress());
 }
Пример #12
0
        public static void Main(string[] args)
        {
            string logPath = Path.GetTempPath();

            logPath  = Path.Combine(logPath, "cPanel");
            logPath += DateTime.Now.ToString("yyyyMMdd-HHmmss");
            logPath += ".log";
            Logger.Setup(logPath);

            Logger.Instance.Write(Logger.Severity.Debug, "Starting up...");

            CmdOptions options = new CmdOptions();

            if (CommandLine.Parser.Default.ParseArguments(args, options) == false)
            {
                Console.WriteLine("Return codes: ");
                Console.WriteLine(BuildReturnString());
                Environment.Exit((int)DDNSReturnCodes.InvalidOptionsGiven);
            }

            // Check if we need to lookup our public IP on the internet
            if (string.IsNullOrEmpty(options.IP))
            {
                Logger.Instance.Write(Logger.Severity.Debug,
                                      "No IP given on the command line, looking up");
                options.IP = PublicIP.Lookup();

                if (options.IP == string.Empty)
                {
                    Logger.Instance.Write(Logger.Severity.Error, "IP Address lookup failed");
                    Environment.Exit((int)DDNSReturnCodes.IPLookupFailure);
                }

                Logger.Instance.Write(Logger.Severity.Debug,
                                      "Got IP: " + options.IP);
            }


            // Setup the cPanelAPI
            cPanelAPI api = new cPanelAPI(options.URL,
                                          options.Username,
                                          options.Password,
                                          options.Secure);

            // Update the domain A record only, point to our IP.
            DDNSResult result;

            result = UpdateDomainARecord(api,
                                         options.Domain,
                                         options.Zone,
                                         options.IP);

            if (result == DDNSResult.NotNeccessary)
            {
                Logger.Instance.Write(Logger.Severity.Debug,
                                      "IP address in record same as given IP, nothing to do");
                Environment.Exit((int)DDNSReturnCodes.NoUpdateNeccessary);
            }
            else if (result == DDNSResult.UpdateSuccess)
            {
                Logger.Instance.Write(Logger.Severity.Debug,
                                      "Successfully updated zone " + options.Zone +
                                      " on domain " + options.Domain +
                                      " to point to IP " + options.IP);
                Environment.Exit((int)DDNSReturnCodes.UpdateSuccess);
            }
            else
            {
                Logger.Instance.Write(Logger.Severity.Error, "Updating zone record has failed");
                Environment.Exit((int)DDNSReturnCodes.GeneralError);
            }
        }
Пример #13
0
        public void WaitUntilDeleted_ThrowsException_WhenCalledOnManuallyCreatedInstance()
        {
            var ip = new PublicIP();

            Assert.Throws<InvalidOperationException>(() => ip.WaitUntilDeleted());
        }
Пример #14
0
 /// <inheritdoc cref="PublicIP.WaitUntilDeletedAsync"/>
 public static void WaitUntilDeleted(this PublicIP publicIP, TimeSpan?refreshDelay = null, TimeSpan?timeout = null, IProgress <bool> progress = null)
 {
     publicIP.WaitUntilDeletedAsync(refreshDelay, timeout, progress).ForceSynchronous();
 }
Пример #15
0
 /// <inheritdoc cref="PublicIP.UnassignAsync"/>
 public static void Unassign(this PublicIP publicIP)
 {
     publicIP.UnassignAsync().ForceSynchronous();
 }
Пример #16
0
 /// <inheritdoc cref="PublicIP.AssignAsync"/>
 public static void Assign(this PublicIP publicIP, string serverId)
 {
     publicIP.AssignAsync(serverId).ForceSynchronous();
 }
Пример #17
0
 /// <inheritdoc cref="PublicIP.DeleteAsync"/>
 public static void Delete(this PublicIP publicIP)
 {
     publicIP.DeleteAsync().ForceSynchronous();
 }