2012-08-14 96 views
0

我正在開發asp.net網站,現在我的問題是如何獲取lan使用c#代碼連接ip地址,例如打開http://whatismyipaddress.com/顯示IP信息:183.82.77.56這樣我就得到了ip地址,現在我是像這樣寫如何使用asp.net獲取網絡ip地址(Internet)?

//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; 
     } 

但錯誤的輸出,請幫助我的任何一個。

感謝ü hemanth

回答

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()); 
      } 
     } 
+0

在那裏我可以添加此代碼,請給我一個例子 – hmk 2012-08-14 06:06:39

+0

低於此line IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName); – 2012-08-14 06:08:35

+1

AddressList count count爲4,1爲{fe80 :: c90d:59f2:6d65:8100%11},2爲{fe80 :: 18d7:2872:3f57:fe35%12},3爲{192.168.1.202} (我的電腦IP),4是{2001:0:9d38:953c:18d7:2872:3f57:fe35}但我有183.82.77.56(這是我的帶寬IP) – hmk 2012-08-14 06:12:36