检查您自己的IP地址

时间:2014-09-03 22:02:36

标签: c# .net

我是新手程序员,我试图检查自己的IP地址。问题是我不喜欢复制粘贴的东西,我真的需要了解我在做什么。在谷歌的帮助下,我认为我理解了大部分内容,但仍有一些不清楚的事情。我非常感谢你的解释。在评论中指出了我不能得到的东西。我也很高兴有人可以检查我的想法(在评论中)是否正确。

using UnityEngine;
using System.Collections;
using System.Net;
/*
 * The System.Net namespace provides a simple programming interface for many of the protocols used on networks today. 
 * The WebRequest and WebResponse classes form the basis of what are called pluggable protocols, an implementation of network services that enables you to develop applications that use Internet resources without worrying about the specific details of the individual protocols.
 * Classes in the System.Net namespace can be used to develop Windows Store apps or desktop apps. When used in a Windows Store app, classes in the System.Net namespace are affected by network isolation feature, part of the application security model used by the Windows Developer Preview. 
 * The appropriate network capabilities must be enabled in the app manifest for a Windows Store app for the system to allow network access by a Windows Store app. For more information, see the Network Isolation for Windows Store Apps.
*/
using System.IO;
//The System.IO namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.
public class PokazIP : MonoBehaviour {

    public string GetLocalIP()
    {
        string localIP = "?";//New variable of string type
        IPHostEntry host;//New variable of IPHostEntry type learn more: http://msdn.microsoft.com/en-us/library/system.net.iphostentry%28v=vs.110%29.aspx
        //IPHostEntry -> Provides a container class for Internet host address information. One of its properties is AddressList.
        //AddressList -> Gets or sets a list of IP addresses that are associated with a host.
        //Learn more http://msdn.microsoft.com/en-us/library/system.net.iphostentry.addresslist%28v=vs.110%29.aspx
        host = Dns.GetHostEntry(Dns.GetHostName());
        /*Dns. a class of System.Net(System.Net.Dns) which provides simple domain name resolution functionality
        learn more: http://msdn.microsoft.com/en-us/library/system.net.dns%28v=vs.110%29.aspx
        .GetHostEntry(hostNameOrAddress -> Type: System.String -> The host name or IP address to resolve.) 
         * method of Dns class which resolves a host name or IP address to an IPHostEntry instance. (Actually I dont really understand this discription.)
         * Return Value -> Type: System.Net.IPHostEntry -> An IPHostEntry instance that contains address information about the host specified in hostNameOrAddress.
         * learn more: http://msdn.microsoft.com/en-us/library/ms143998%28v=vs.110%29.aspx
        .GetHostName() method of Dns class which gets the host name of the local computer.
         * Return Value -> Type: System.String -> A string that contains the DNS host name of the local computer.
         * learn more: http://msdn.microsoft.com/en-us/library/system.net.dns.gethostname%28v=vs.110%29.aspx
        */
        foreach (IPAddress ip in host.AddressList)//**New variable called ip of type IPAddress. host.AddressList is made of IPAddress objects???**
        //Properties of IPAdress: Address and AddressFamily
        //learn more http://msdn.microsoft.com/en-us/library/system.net.ipaddress%28v=vs.110%29.aspx
        {
            if (ip.AddressFamily.ToString() == "InterNetwork")//**Whats InterNetwork? Why do we look for that in ip?**
            {
                localIP = ip.ToString();//obvious
                break;//**so if it finds "InterNetwork" it is not looking further 'coz its not needed?**
            }
        }
        return localIP;//returns IP
    }
    public string GetPublicIP()
        /*
         * This funcion is using checkip server to tell you yours IP.
         * I guess it is because for some reason we cant do it from our computer. Why?
         */
    {
        string direction = "";//New variable of type string
        WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
        /*
         * WebRequest.Create Method (String)
         * Initializes a new WebRequest instance for the specified URI scheme.
         * http://msdn.microsoft.com/en-us/library/bw00b1dc%28v=vs.110%29.aspx
         * WebRequest is a class of System.Net
         * Makes a request to a Uniform Resource Identifier (URI). This is an abstract class. <- I dont really get it to many unknown things :S
         * http://msdn.microsoft.com/en-us/library/system.net.webrequest%28v=vs.110%29.aspx
         */
        using (WebResponse response = request.GetResponse())
        /*
         * Why "using"?
         * WebResponse is a class of System.Net
         * Provides a response from a Uniform Resource Identifier (URI). This is an abstract class. <- I dont really get it to many unknown things :S
         * http://msdn.microsoft.com/en-us/library/system.net.webresponse%28v=vs.110%29.aspx
         * GetResponse() is a method of WebRequest
         * When overridden in a descendant class, returns a response to an Internet request.
         */
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        //Again why using?
        //Creating new StreamReader object named stream with value response.GetResponseStream()
        //.GetResponseStream() is WebResponse. method
        //When overridden in a descendant class, returns the data stream from the Internet resource.
        {
            direction = stream.ReadToEnd();
            //StreamReader.ReadToEnd Method
            //Reads all characters from the current position to the end of the stream.
        }
        //This is how the web page looks like
        //<html><head><title>Current IP Check</title></head><body>Current IP Address: 89.71.166.131</body></html>
        int first = direction.IndexOf("Address: ") + 9;//"Address: " it is 9 chars
        int last = direction.LastIndexOf("</body>");
        direction = direction.Substring(first, last - first);

        return direction;
    }
    void OnGUI()//Displaying it on the "screen"
    {
        GUI.Label(new Rect(80f, 50f, 100f, 25f), GetLocalIP());
        GUI.Label(new Rect(80f, 100f, 100f, 25f), GetPublicIP());
    }
}

2 个答案:

答案 0 :(得分:1)

&#34;互联网络&#34;表示IPv4,请参阅System.Net.Sockets.AddressFamily。

John Saunders所说的问题是你的计算机可能有多个ip,例如你可能有一个连接到网络的wifi卡和一个用以太网电缆连接到另一个网络的以太网卡。

第二种方法:&#34; GetPublicIP()&#34;,尝试连接到远程服务器以查找您的IP。 今天大多数有互联网的房屋都使用路由器连接到互联网,这就是为什么你无法从计算机上获取外部或公共IP(你的路由器有公共IP而不是你的电脑)。

答案 1 :(得分:-1)

首先,说实话,很少有人会阅读你的所有评论并回答它们。这可能更适合https://meta.stackoverflow.com/。他们专注于高级别的会话,而不是实际的代码问题。

但回答你的一个反复出现的问题。我发现你经常会问&#34;为什么要使用&#34;。当代码离开using语句时,C#中的using语句会自动关闭连接。因此,您经常会看到它与连接相关的对象(即sqlconnection或streamreader等)一起使用。如果没有使用,用户将需要显式处理这些对象以关闭连接。另外作为旁注,即使代码在using语句中失败,它仍将处理/关闭正在使用的对象。