IP转换为字节/转换回字符串转换为、字符串、字节、IP

2023-09-03 17:07:52 作者:努力↗才会幸福

我在2008年SQLSERVER数据库作为二进制存储IPv4地址(4)。所以,我的数据输入转换前的值(并且由于公司限制,我无法创建功能的数据库里面,还有那不是再讨论)。

I'm storing an IPV4 address on a SQLSERVER 2008 database as Binary(4). So, I'm converting the values before data input (and due to company restrictions I CANNOT create functions inside the db, well thats not up for discussion).

public static byte[] IpToBin(string ip)
{
    return IPAddress.Parse(ip).GetAddressBytes();
}

public static string HexToIp(string ip)
{
    return new IPAddress(long.Parse(ip, NumberStyles.HexNumber)).ToString(); 
}

IpToBin称为后,所产生的数据是(例如0x59FC09F3)。当我打电话HexToIp的IP颠倒过来可能是由于小/大端转换。

After IpToBin is called, the data generated is (for example 0x59FC09F3). When I call HexToIp the ip came reversed probably due little/big endian conversion.

任何人都可以,请拿出一个像样的解决方案,不带50十亿行code?

Could anyone please come up with a decent solution without 50 billion lines of code?

推荐答案

我觉得这里真正的问题是,你正在处理的原始形式的字符串;特别是因为它是二进制(4),你不应该这样做:只是把它抓回来从DB作为字节[] IpToBin 是好的,但 HexToIp 也许应该是:

I think the real issue here is that you are treating the raw form as a string; especially since it is binary(4), you should never have to do that: just fetch it back from the db as a byte[]. IpToBin is fine, but HexToIp should probably be:

public static IPAddress BinToIp(byte[] bin)
{
    return new IPAddress(bin);
}

那么:完成任务。但是,与现有的 HexToIp code,你想要的:

then: job done. But with your existing HexToIp code, you want:

return new IPAddress(new byte[] {
    Convert.ToByte(ip.Substring(0,2), 16), Convert.ToByte(ip.Substring(2,2), 16),
    Convert.ToByte(ip.Substring(4,2), 16), Convert.ToByte(ip.Substring(6,2), 16)}
    ).ToString(); 
 
精彩推荐
图片推荐