Advertisement
danielhilst

printiphex.c

Sep 19th, 2013
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.03 KB | None | 0 0
  1. /**
  2.  * @brief convert IP from network format to string, if
  3.  *        the only parameter starts with 0x, e.g.
  4.  *        ./printiphex 0x0100007F
  5.  *        => 127.0.0.1
  6.  *        or print the address on network notation otherwise e.g.
  7.  *        ./printiphex 127.0.0.1
  8.  *        => 0x0100007F
  9.  *
  10.  * @param 1th, The ip address to convert from network to
  11.  *             string or reverse.
  12.  *
  13.  */
  14.  
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <stdlib.h>
  18. #include <sys/socket.h>
  19. #include <netinet/in.h>
  20. #include <arpa/inet.h>
  21.  
  22. #define pexit(s) ({perror(s); exit(EXIT_FAILURE);})
  23.  
  24. int main(int argc, char **argv)
  25. {
  26.         if (argc < 2) {
  27.                 printf("Usage: %s IP\n", argv[0]);
  28.                 exit(EXIT_FAILURE);
  29.         }
  30.  
  31.         if (!strncmp("0x", argv[1], 2)) {
  32.                 struct in_addr addr = {
  33.                         .s_addr = strtol(argv[1], NULL, 16),
  34.                 };
  35.  
  36.                 printf("%s\n", inet_ntoa(addr));
  37.         } else {
  38.                 printf("0x%08X\n",  inet_addr(argv[1]));
  39.         }
  40.  
  41.         return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement