如何将IPv4地址转换成C#中的整数? [英] How to convert an IPv4 address into a integer in C#?
问题描述
我在寻找,将一个标准的IPv4地址转换为整数的函数。可用于该会得到相反的函数积分。
解决方案应该在C#。
//的IPv4
INT intAddress = BitConverter.ToInt32(IPAddress.Parse(地址).GetAddressBytes(),0);
。字符串ip地址=新的ip地址(BitConverter.GetBytes(intAddress))的ToString();
编辑:正如在其他的答案指出,运行一个小端机器上的这个片段时,它会给出相反的顺序字节的标准定义。然而,问题要求一个整数和一个IP地址,不转换成标准整数格式之间的映射。要做到这一点,你必须考虑你正在运行的机器的字节序。
I'm looking for a function that will convert a standard IPv4 address into an Integer. Bonus points available for a function that will do the opposite.
Solution should be in C#.
// IPv4
int intAddress = BitConverter.ToInt32(IPAddress.Parse(address).GetAddressBytes(), 0);
string ipAddress = new IPAddress(BitConverter.GetBytes(intAddress)).ToString();
EDIT: As noted in other answers, when running this snippet on a little endian machine, it'll give out the bytes in the reverse order as defined by the standard. However, the question asks for a mapping between an integer and an IP address, not converting to the standard integer format. To do so, you have to consider the endian-ness of the machine you're running on.
这篇关于如何将IPv4地址转换成C#中的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!