2011-12-16 2 views
0

그래서 나는 두 개의 IP 주소를 사용하고 각각을 비교하여 어떤 주소가 ping되어야 하는지를 계산하는 범위 핑거를 만들려고합니다.사용자 입력에서 범위를 확인하는 올바른 범위의 핑거 알고리즘은 무엇입니까?

문제는 하루 종일 아무 것도 생각해 내지 못했던 코드를 만드는 방법을 생각한 이후로 내가 여기 왔음을 의미합니다.

예를 들어 192.168.0.1에서 192.168.1.1까지의 주소 범위를 가지고 있습니다. 즉, 254 개의 IP 주소를 핑합니다.

어떻게 이런 일이 벌어 질까요?

IF 문을 확인해야하는 항목은 무엇입니까?

지금 현재 나는이있다 :

public partial class PingIPRange : Form 
{ 
    public PingIPRange() 
    { 
     InitializeComponent(); 

     txtFrom.Text = "74.125.225.20"; 
     txtTo.Text = "74.125.225.30"; 
    } 

    private void btnPing_Click(object sender, EventArgs e) 
    { 
     //for (int i = 0; i < int.Parse(txtRepeat.Text); i++) 
     //{ 
      CalculateRange(txtFrom.Text, txtTo.Text); 
     //} 
    } 

    private void CalculateRange(string addressFrom, string addressTo) 
    { 
     int max = 10; 
     int min = 0; 

     int from1 = 0; 
     int from2 = 0; 
     int from3 = 0; 
     int from4 = 0; 

     int to1 = 0; 
     int to2 = 0; 
     int to3 = 0; 
     int to4 = 0; 

     var from = txtFrom.Text.Split('.'); 
     var to = txtTo.Text.Split('.'); 

     if (from.Length == 4) 
     { 
      from1 = int.Parse(from[0]); 
      from2 = int.Parse(from[1]); 
      from3 = int.Parse(from[2]); 
      from4 = int.Parse(from[3]); 
     } 

     if (to.Length == 4) 
     { 
      to1 = int.Parse(to[0]); 
      to2 = int.Parse(to[1]); 
      to3 = int.Parse(to[2]); 
      to4 = int.Parse(to[3]); 
     } 

     if (from1 == to1 && from2 == to2 && from3 == to3 && from4 == to4) 
     { 
      Ping(string.Format("{0}.{1}.{2}.{3}", from1, from2, from3, from4)); 
     } 
     else 
     { 
     } 


    } 

    private void Ping(string address) 
    { 
     Ping pingSender = new Ping(); 
     PingOptions options = new PingOptions(); 
     options.DontFragment = true; 
     // Create a buffer of 32 bytes of data to be transmitted. 
     string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; 
     byte[] buffer = Encoding.ASCII.GetBytes(data); 
     int timeout = 120; 
     try 
     { 
      PingReply reply = pingSender.Send(address, timeout, buffer, options) ; 
      if (reply.Status == IPStatus.Success) 
      { 
       /*PingReply replyy = pingSender.Send(address, timeout, buffer, options); 
       if (reply.Status == IPStatus.Success) 
       { 
        txtDisplay.Text += "IP: " + replyy.Address.ToString() + ". " 
         + "Round Trip: " + replyy.RoundtripTime + ". " 
         + "TTL: " + replyy.Options.Ttl + ". " 
         + "Don't Fragment: " + replyy.Options.DontFragment + ". " 
         + "Buffer Size: " + replyy.Buffer.Length + ". "; 
       }*/ 

       txtDisplay.Text += "Host " + address + " is open." + Environment.NewLine; 
      } 
      else 
      { 
       txtDisplay.Text += "Host " + address + " is closed." + Environment.NewLine; 
      } 
     } 
     catch (Exception ex) 
     { 
      txtDisplay.SelectedText += Environment.NewLine + ex.Message; 
     } 
    } 
} 
+0

여기에 * 모든 * 길을 찾아야했습니다! – Kris

+0

@Kris : 예, 케이블 길이가 길습니다. D 그러나이 문제로 내 마음을 감싸는 방식으로이 구문을 만드는 데 문제가 있습니다. – NewHelpNeeder

+0

마침내, 당신은 해결책을 찾았습니다. 해결 된 것 같습니다. :) – Kris

답변

3

을 나는 '.

static uint str2ip(string ip) 
{ 
    string[] numbers = ip.Split('.'); 

    uint x1 = (uint)(Convert.ToByte(numbers[0]) << 24); 
    uint x2 = (uint)(Convert.ToByte(numbers[1]) << 16); 
    uint x3 = (uint)(Convert.ToByte(numbers[2]) << 8); 
    uint x4 = (uint)(Convert.ToByte(numbers[3])); 

    return x1 + x2 + x3 + x4; 
} 

and 

static string ip2str(uint ip) 
{ 
    string s1 = ((ip & 0xff000000) >> 24).ToString() + "."; 
    string s2 = ((ip & 0x00ff0000) >> 16).ToString() + "."; 
    string s3 = ((ip & 0x0000ff00) >> 8).ToString() + "."; 
    string s4 = (ip & 0x000000ff).ToString(); 

    string ip2 = s1 + s2 + s3 + s4; 
    return ip2; 
} 

쉽게 모든 IP를 반복 할 수이 방법 : D 번호와 그 반대에 IP 주소를 변환하는 두 가지 기능을합니다. 다음은 샘플 프로그램이 있습니다 :

static void Main(string[] args) 
{ 
    uint startIP = str2ip("250.255.255.100"); 
    uint endIP = str2ip("255.0.1.255"); 

    for(uint currentIP = startIP; currentIP <= endIP; currentIP++) { 
     string thisIP = ip2str(currentIP); 
     Console.WriteLine(thisIP); 
    } 

    Console.ReadKey(); 
} 
+0

이것은 흥미로운 것 같습니다. 나는 그것을 내일 시도 할 것이다. – NewHelpNeeder

+1

이것은 매우 좋습니다! '(ip & 0xff000000) >> 24)'- 비트가 1이고'uint '가 아닌'int'를 사용하고 있다면, >> >>를 채우지 않습니다. 왼쪽에서 '1'로? – Rawling

+0

@ Rawling : 네, 맞습니다. 고마워요. 매우 영리한 발언! :) – BlackBear

1

여기서 가장 큰 문제는 IP 주소를 증가하는 것입니다. C# 코드가 아닌 알고리즘으로 다음을 수행 할 수 있습니다.

  • 네 번째 int (예 : from4)를 증가시킵니다.
  • 네 번째 int가 256 인 경우 0으로 설정하고 세 번째 int를 증가시킵니다. 그렇지 않으면 다음 IP 주소가 있습니다.
  • 세 번째 int가 256 인 경우 0으로 설정하고 두 번째 int를 증가시킵니다. 그렇지 않으면 다음 IP 주소가 있습니다.
  • 두 번째 int가 256이면 0으로 설정하고 첫 번째 int를 증가시킵니다. 그렇지 않으면 다음 IP 주소가 있습니다.
  • 첫 번째 int가 256 인 경우 0으로 설정하십시오. 이 시점에서 0.0.0.0으로 감싼 것처럼 멈 춥니 다. to 주소는 from 주소 앞에 있습니다.

이제 다음 IP 주소를 가지고 - 그래서 당신은 당신의 to IP 주소에 대해 그것을 확인하고이 코드에 어떤 루프 밖으로 파괴함으로써, 또는 마무리 핑 여부를 확인할 수 있습니다

+0

이것은 합리적인 것처럼 보입니다. – NewHelpNeeder

+0

아, 기본적으로 내 'to'주소에서 내 'to'주소에 도달 할 때까지이 IP 증분을 수행합니다. – NewHelpNeeder

+0

그래 ... 원하는지 여부에 따라 '보낸 사람'또는 '받는 사람'주소를 ping하지 않거나하지 않도록 경계에주의하십시오. – Rawling

0

이 기본 비주얼한다면 나는 질문에 맞설 수있는 서브넷 경계가 있는지 이야기하기 어려운이

Public Class Form1 

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
     Dim startIP As New anIP("192.168.0.1") 
     Dim endIP As New anIP("192.168.1.1") 

     For x As Integer = startIP.asNumber To endIP.asNumber 
      Dim foo As New anIP(x) 
      Debug.WriteLine(foo.asString) 
     Next 
    End Sub 

    Class anIP 
     Property asNumber As Integer 
     Property asAddr As Net.IPAddress 
     Property asBytes As Byte() 
     Property asString As String 

     Public Sub New(ipString As String) 
      Try 
       Me.asAddr = Net.IPAddress.Parse(ipString) 
       Me.asBytes = Me.asAddr.GetAddressBytes 
       Array.Reverse(Me.asBytes) 
       Me.asNumber = BitConverter.ToInt32(Me.asBytes, 0) 
      Catch ex As Exception 
       Throw 
      End Try 
     End Sub 

     Public Sub New(ipNumber As Integer) 
      Me.asBytes = BitConverter.GetBytes(ipNumber) 
      Array.Reverse(Me.asBytes) 
      Me.asAddr = New Net.IPAddress(Me.asBytes) 
      Me.asString = Me.asAddr.ToString 
     End Sub 
    End Class 
End Class 

할 것입니다.

+0

VB를 수행하는 방법을 알고있는 경우에만 : / – NewHelpNeeder

관련 문제