0

私はasp.netWebサイトを開発していますが、問題はc#コードを使用してLAN接続されたIPアドレスを取得する方法です。たとえば、http://whatismyipaddress.com/を開いてIP情報を表示します。アドレス、今私はこのように書いています

//Get Lan Connected IP address method
        public string GetLanIPAddress()
        {
            //Get the Host Name
            string stringHostName = Dns.GetHostName();
            //Get The Ip Host Entry
            IPAddress[] arrIpAddress1 = Dns.GetHostAddresses(stringHostName);

            IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
            //Get The Ip Address From The Ip Host Entry Address List
            IPAddress[] arrIpAddress = ipHostEntries.AddressList;
            return arrIpAddress[arrIpAddress.Length - 1].ToString();
        }
        //Get Visitor IP address method
        public string GetVisitorIpAddress()
        {
            string stringIpAddress;
            stringIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (stringIpAddress == null) //may be the HTTP_X_FORWARDED_FOR is null
            {
                stringIpAddress = Request.ServerVariables["REMOTE_ADDR"];//we can use REMOTE_ADDR
                string add = HttpContext.Current.Request.UserHostAddress;
            }
            return "Your ip is " + stringIpAddress;
        }

しかし、間違った出力、私を助けてください。

ありがとうヘマンス

4

1 に答える 1

0

このコードを追加する

        foreach (IPAddress ipaddress in ipHostEntries.AddressList)
        {
            IPStr = ipaddress.ToString();
            return IPStr;
        }
        return IPStr;

このゲートウェイアドレスを試してください

   IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
        Console.WriteLine(ipProperties.HostName);

        foreach (NetworkInterface networkCard in NetworkInterface.GetAllNetworkInterfaces())
        {
            foreach (GatewayIPAddressInformation gatewayAddr in networkCard.GetIPProperties().GatewayAddresses)
            {
                Console.WriteLine("Information: ");
                Console.WriteLine("Interface type: {0}", networkCard.NetworkInterfaceType.ToString());
                Console.WriteLine("Name: {0}", networkCard.Name);
                Console.WriteLine("Id: {0}", networkCard.Id);
                Console.WriteLine("Description: {0}", networkCard.Description);
                Console.WriteLine("Gateway address: {0}", gatewayAddr.Address.ToString());
                Console.WriteLine("IP: {0}", System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0].ToString());
                Console.WriteLine("Speed: {0}", networkCard.Speed);
                Console.WriteLine("MAC: {0}", networkCard.GetPhysicalAddress().ToString());
            }
        }
于 2012-08-14T05:58:52.297 に答える