Conversion of address forms in Linux network communication

Source: Internet
Author: User


For the IPV4 protocol, IP is a 32-bit integer, and for IPv6, IP is a 128-bit integer. In memory, IP is stored in binary form, but not easy to observe, so
OKconversion translates it into a dotted-decimal representation.
In Linux, there are functions for converting IP binary and dotted decimal to each other:

Inet_ntop the binary into dotted decimal, AF represents the protocol used, and af_inet indicates that the IPV6,SRC used is a IPV4,AF_INET6 that represents the IP

struct in_addr, DST is the string used to store the IP dotted decimal form, and the size is the length of the DST.


Inet_pton is used to convert the dot decimal of an IP into a binary representation, AF indicates whether it is IPV4 or IPV6,SRC is a string that stores IP dotted decimal, DST is a storage IP
struct IN_ADDR type structure body.
  
 
  1. #include<stdio.h>
  2. #include<arpa/inet.h>
  3. #include<stdlib.h>
  4. void pton(const char* src)
  5. {
  6. struct in_addr addr;
  7. int temp = inet_pton(AF_INET,src,&addr);
  8. if(temp<=0)
  9. {
  10. perror("fail to convert");
  11. exit(-1);
  12. }
  13. printf("convert success,ip:%x\n",addr.s_addr);
  14. }
  15. void ntop(struct in_addr addr)
  16. {
  17. Span class= "KWD" >char DST [ 16 Span class= "pun" >]={ 0 }; //255.255.255.255 3*4+3 ('. ') +1 (' =16 ')
  18. const char* temp = inet_ntop(AF_INET,&addr,&dst,sizeof(dst));
  19. if(temp==NULL)
  20. {
  21. perror("fail to convert");
  22. exit(-1);
  23. }
  24. printf("convert success,ip:%s\n",dst);
  25. }
  26. int main()
  27. {
  28. pton("192.168.1.24");
  29. struct in_addr addr;
  30. addr.s_addr = 0x1801a8c0;
  31. ntop(addr);
  32. return 0;
  33. }




From for notes (Wiz)

Conversion of address forms in Linux network communication

Related Article

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.