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.

 

posted @ 2015-09-07 16:29  ChuckLu  阅读(365)  评论(0编辑  收藏  举报