C/C ++ obtains the IP address of the local machine.

Source: Internet
Author: User
Tags name database
/* Compiling environment: Visual C ++ */
  1. # Include <stdio. h>
  2. # Include <winsock2.h>
  3. # Pragma comment (Lib, "ws2_32.lib ")
  4. Int doit (INT, char **)
  5. {
  6. Char host_name [2, 255];
  7. // Obtain the local host name
  8. If (gethostname (host_name, sizeof (host_name) = socket_error ){
  9. Printf ("error % d when getting local host name./N", wsagetlasterror ());
  10. Return 1;
  11. }
  12. Printf ("host name is: % s/n", host_name );
  13. // Obtain the corresponding "host" from the host name database"
  14. Struct hostent * Phe = gethostbyname (host_name );
  15. If (PHE = 0 ){
  16. Printf ("yow! Bad host lookup .");
  17. Return 1;
  18. }
  19. // Cyclically obtain all IP addresses of the Local Machine
  20. For (INT I = 0; phe-> h_addr_list [I]! = 0; ++ I ){
  21. Struct in_addr ADDR;
  22. Memcpy (& ADDR, Phe-> h_addr_list [I], sizeof (struct in_addr ));
  23. Printf ("address % d: % s/n", I, inet_ntoa (ADDR ));
  24. }
  25. Return 0;
  26. }
  27. Int main (INT argc, char * argv [])
  28. {
  29. Wsadata;
  30. If (wsastartup (makeword (1, 1), & wsadata )! = 0 ){
  31. Return 255;
  32. }
  33. Int retval = doit (argc, argv );
  34. Wsacleanup ();
  35. Return retval;
  36. }

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.