Convert an IP address to binary data without calling the library function.

Source: Internet
Author: User

Int inet_aton (const char * CP)
{
Int DOTS = 0;
Int A [32] = {0 };
Register unsigned long ACC = 0, ADDR = 0;
Do {
Register char cc = * CP;
Switch (cc)
{
Case '0 ':
Case '1 ':
Case '2 ':
Case '3 ':
Case '4 ':
Case '5 ':
Case '6 ':
Case '7 ':
Case '8 ':
Case '9 ':
ACC = ACC * 10 + (CC-'0 ');
Break;
Case '.':
If (++ dots> 3)
{
Return 0;
}
// Fall through
Case '\ 0 ':
If (ACC> 255)
{
Return 0;
}
ADDR = ADDR <8 | ACC; // This sentence is the essence. Each time you move the current value to the left eight places and add the following value ADDR, the final result is an unsigned long integer.
ACC = 0;
Break;
Default:
Return 0;
}
} While (* CP ++ );
// Normalize the address
If (DOTS <3)
{
ADDR <= 8 * (3-dots );
}

Int K = 0;
While (ADDR)
{
A [k ++] = ADDR % 2;
ADDR/= 2;
}
For (int K = 31; k> = 0; k --)
{
Cout <A [k];
If (K % 8 = 0)
{
Cout <"";
}
}
Return 1;
}

Convert an IP address to binary data without calling the library function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.