2016-03-18 189 views

回答

1

以下是您的解決方案。首先將IP地址轉換爲數字,然後得到HEX值。您可能想要將HEX轉換爲IP,可能將來會出現,因此此鏈接爲Resource for IP conversions that I use.請參見下面的輸出。

public class Program 
{ 
    static void Main(string[] args) 
    { 
     string ip = "192.168.232.189"; 
     string ipHexFormat = string.Format("{0:X}", ConvertIpToNumber(ip)); 

     Console.WriteLine(ipHexFormat); 
    } 

    public static long ConvertIpToNumber(string dottedIpAddress) 
    { 

     long num = 0; 
     if (dottedIpAddress == "") 
     { 
      return 0; 
     } 
     else 
     { 
      int i = 0; 
      string[] splitIpAddress = dottedIpAddress.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); 
      for (i = splitIpAddress.Length - 1; i >= 0; i--) 
      { 
       num += ((long.Parse(splitIpAddress[i]) % 256) * (long)Math.Pow(256, (3 - i))); 
      } 
      return num; 
     } 
    } 
} 

輸出 enter image description here

0

在這裏你去

string ip = "192.168.232.189"; 
string hex = string.Concat(ip.Split('.').Select(x => byte.Parse(x).ToString("X2"))); 
  • .拆分IP串與string.Split()
  • byte.Parse()解析每個字節
  • string.Concat()
1

轉換byte爲十六進制字符串ToString("X2")

  • 合併所有十六進制字符串連接在一起通過使用IPAddress類來解析地址(解析永遠是最複雜的部分):

    IPAddress address = IPAddress.Parse("192.168.232.189"); 
    
    // Otherwise IPAddress would parse even IPv6 addresses 
    if (address.AddressFamily != AddressFamily.InterNetwork) 
    { 
        throw new ArgumentException("address"); 
    } 
    
    byte[] bytes = address.GetAddressBytes(); 
    string strAddress = string.Format("{0:X2}{1:X2}{2:X2}{3:X2}", bytes[0], bytes[1], bytes[2], bytes[3]); 
    
  • 1

    每段IP地址相當於2個十六進制數字(或8個二進制數字)。 所以你的問題歸結爲分割192.168.232.189到192,168,232,189。然後轉換每一塊(簡單的十進制 - 十六進制轉換),並把它放回在一起。

    0

    您可以使用System.Net.IPAddress

    IPAddress ip = IPAddress.Parse("192.168.232.189"); 
        Console.WriteLine(ByteArrayToString(ip.GetAddressBytes())); 
    
    public static string ByteArrayToString(byte[] ba) 
    { 
        string hex = BitConverter.ToString(ba); 
        return hex.Replace("-",""); 
    } 
    

    這裏是demo

    1

    如果IP地址被表示爲String,你想有一個String結果可以

    1. 拆分原始字符串由'.'分成IP地址部分
    2. 轉換各部分int
    3. 代表每個部分作爲十六進制具有至少2個兩個數字
    4. 的毗連所有部件一起

    可能的實現(LINQ的)是

    String address = "192.168.232.189"; 
    
    // "C0A8E8BD" 
    String result = String.Concat(address.Split('.').Select(x => int.Parse(x).ToString("X2"))); 
    
    相關問題