How to convert an IPv4 address into a integer in C#?

仅仅针对于IPv4的处理方法

从string转换为int

以及从int转换为string

// 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.

上一篇:C中extern的用法


下一篇:新概念英语(1-67)The weekend