IP address format conversion

Source: Internet
Author: User

First, we will use the Linux interface to convert unsigned Int or unsigned long data to the point-to-decimal method:
1. The declaration of the inet_ntoa () function is included in the/usr/include/ARPA/inet. h file:
Extern char * inet_ntoa (struct in_addr _ In) _ Throw;
_ In: struct variable of struct in_addr.
So what is this struct variable? Let's take a look:
Struct in_addr
{
Unsigned long s_addr;
};
Therefore, in fact, the in_addr struct is a variable of the unsigned long type used to render a person.
OK. We use code to convert IP addresses:
# Include <stdio. h>
# Include <ARPA/inet. h>
# Include <netinet/in. h>

Int main ()
{
Struct in_addr myaddr, testaddr;
Unsigned int addr_test = inet_addr ("192.168.1.20 ");
Unsigned int IP = 1174448320; // random unsigned int value, of course, it must be an IP address.
// This inet_addr () is actually converting the IP address in dotted decimal format to an unsigned int type, which is opposite to inet_ntoa (struct in_addr.
Memcpy (& myaddr, & addr_test, 4 );
Memcpy (& testaddr, & IP, 4 );
Printf ("the IP is: % s/n", inet_ntoa (myaddr ));
Printf ("the IP is: % s/n", inet_ntoa (testaddr ));
Return 0;
}
So this is a way to convert the IP address format.
Note: The Return Value in the inet_ntoa (struct in_addr) interface is the static variable defined. Static allocation is easily overwritten.

Then, we will use a function to convert the IP address written by ourselves: it indicates robustness, so write a specification.
Struct ipaddr
{
Unsigned char IP1;
Unsinged char ip2;
Unsigned char IP3;
Unsigned char ip4;
} Ipaddr;

Int uint_to_ip (struct ipaddr * IPA, unsigned int IP)
{
IPA-> IP1 = 0;
IPA-> ip2 = 0;
IPA-> IP3 = 0;
IPA-> ip4 = 0;
IP-> IP1 = (ip> 0) & 0xff;
IP-> ip2 = (ip> 8) & 0xff;
IP-> IP3 = (ip> 16) & 0xff;
IP-> ip4 = (ip> 24) & 0xff;
}

Then write a printf ("% d. % d. % d. % d/N ", IPA-> IP1, IP-> ip2, IP-> IP3, IP-> ip4); OK ..
Do you think it is quite simple...

Thanks.

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.