将号码转换为IP地址(v4)

时间:2017-02-13 12:00:03

标签: vb.net network-programming ip-address

我试图将四位数转换为IP地址。例如:

0001 ---> * .192.1.01

0011 ---> * .192.11.01

0111 ---> * .192.111.01

1111 ---> * .196.87.01

3458 ---> * .205.130.01

我认为子网掩码是255.255.192.0。

我非常感谢有关在vb.net中执行此操作的最佳方法的任何建议。

其他信息:

这是一个简单的pinger程序,用户输入一个四位数字(他们想要ping的物理站点的ID).IP寻址方案很简单,第二个和第二个。第3个八位字节用作站点编号,第四个八位字节用作站点上的设备。我没有设计这个方案,因此我不确定如何让vb.net理解它。

我尝试过的事情:

我考虑过以下方式,这是非常粗糙的。然而,这只能达到* .192.255.01,因为我不知道如果在八位字节3中超过255之后如何分割两个八位字节之间的数字。

Private Sub btnStartPing(sender As Object, e As EventArgs) Handles btnStartPing.Click

    Dim Octet1 As Integer = *
    Dim Octet2 As Integer = 192
    Dim Octet3 As Integer = txtSiteID.text
    Dim Octet4 As Integer = 01
    Dim CompleteIP As String = ""

    CompletIP = Octet1 & "." & Octet2  & "." & Octet3 & "." & Octet4 

    'PING CompleteIP

end sub

解决方案:

        Dim var1 As Integer = Fix(192 + (NumericUpDown1.Value / 256))
        Dim var2 As Integer = Fix((NumericUpDown1.Value Mod 256))

        MsgBox("Your IP address is: " & "10." & var1 & "." & var2 & "." & "200")
    End Sub

2 个答案:

答案 0 :(得分:0)

您需要将数字分成两部分。获取前半部分并将它们添加到192,然后直接使用后半部分。

    Dim number As Integer

    number = 1
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.192.1.01

    number = 11
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.192.11.01

    number = 111
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.192.111.01

    number = 1111
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.196.87.01

    number = 3458
    Console.WriteLine("*.{0}.{1}.01", 192 + ((number And &HFF00) >> 8), number And &HFF) ' *.205.130.01

取数字并将其拆分为两个

  

3458 = 0x0D82

     

0X0D
    为0x82

然后将192添加到第一部分

  

0x0D + 192 = 205
    0x82 = 130

答案 1 :(得分:0)

这应该是它

Public Function StartPing(txtSiteId As String) As String
    Dim SiteId As Integer = Integer.Parse(txtSiteId)

    'backslash performs integer division (no fractionary part)
    'will throw an error when SiteId results in values greater than 255
    'type Byte allows only values from 0 to 255
    Dim Octet2 As Byte = 192 + (SiteId \ 256)

    'Mod gets rest of division
    Dim Octet3 As Byte = SiteId Mod 256

    Return String.Format("*.{0}.{1}.01", Octet2, Octet3)
End Function