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.