2014-11-02 2 views
-1

사용자가 웹 사이트를 가져와 사용자가 입력 한 웹 사이트의 IP 주소를 얻으려고합니다. 사용자가 모든 웹 사이트를 입력 할 수있는 텍스트 상자가 있습니다. 사용자가 "www.Google.com"을 입력하면 그 텍스트는 System.Net.Dns.GetHostAddresses(Convert.ToString(urlTextbox));이됩니다. 그러나 이것을 실행하고 프로그램을 테스트하면 소켓 처리되지 않은 오류가 발생합니다. 해당 호스트가 없습니다. 이 문제를 해결하려면 어떻게해야합니까?URL에서 IP 주소를 가져 오는 중 소켓 오류가 발생했습니다.

이 내가 원하는 것입니다 :

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net; 
namespace Challenger 
{ 
    public partial class Form1 : Form 
    { 
     int ipWidth; 
     string x; 
     public Form1() 
     { 
      InitializeComponent(); 
      urlTextbox.Text ="www."; 
      ipLabelText();     
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      System.Net.IPAddress[] addresses = 
       System.Net.Dns.GetHostAddresses(Convert.ToString(urlTextbox)); 
      string ipTextLength = Convert.ToString(addresses[0]); 

      //Stores the amount of digits 
      ipWidth = ipTextLength.Length; 

      //Puts ip into a string-> Label for Display 
      label2.Text = Convert.ToString(addresses[0]); 
      label2.Location = new Point(80, 20); 
     } 

     public void ipLabelText() 
     { 
      label2.Parent = panel1; 
      label2.BackColor = Color.Transparent; 
      label2.ForeColor = Color.White; 
     } 
    } 
} 
//Porting LOIC Android Application in C# 

답변

0

GetHostByAddress IP 주소를 받아 호스트 이름을 반환 이 내 코드입니다. 따라서 8.8.8.8을 입력하면 Google DNS 서버의 이름이 반환됩니다. 당신이 찾고있는 방법은 다음과 같습니다 getHostEntry

Microsoft의 예는 다음과 같습니다

public static void DoGetHostEntry(string hostname) 
{ 
    IPHostEntry host; 
    host = Dns.GetHostEntry(hostname); 
    Console.WriteLine("GetHostEntry({0}) returns:", hostname); 
    foreach (IPAddress ip in host.AddressList) 
    { 
     Console.WriteLine(" {0}", ip); 
    } 
} 
+0

해당 코드는'GetHostByAddress'를 사용하지 않습니다. 그리고 OP가 단지 IP 주소 만 필요로한다면'GetHostAddresses' 메쏘드 (사용되는 _is)는 적어도 유효한 호스트 이름으로 호출 될 때 잘 동작합니다. :) –

0

좋은 방법은 디버거에서 볼 수있는 코드를 단계별로하는이되었을 것이다 연구 한 것으로 무엇을 실제로는이 Dns.GetHostAddresses() 방법으로 이어지는 입니다.

이렇게하면 Convert.ToString(urlTextbox) 콜은 "System.Windows.Controls.TextBox : www.Google.com"과 비슷한 문자열을 반환한다는 것을 알았을 것입니다. 보시다시피 유효한 호스트 이름은 거의 없습니다. DNS 오류가 발생하는 것은 놀랄 일이 아닙니다. :)

대신 Dns.GetHostAddresses(urlTextbox.Text)을 시도하십시오.

관련 문제