Frage

I have a simple program in C, which resolves IP addresses into hostnames.

#include <stdio.h>          /* stderr, stdout */
#include <netinet/in.h>     /* in_addr structure */
#include <strings.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char **argv) {

if ( argc == 2) {

  struct sockaddr_in sa;
  sa.sin_family = AF_INET;
  inet_pton(AF_INET, argv[1], &sa.sin_addr);

  char node[NI_MAXHOST];
  int res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
  if (res)
  {
    printf("&#37;s\n", gai_strerror(res));
    return 1;
  }
  printf("%s\n", node);

  return 0;
 }
}

It works fine (i.e. ./a.out 10.1.1.2) but I need to modify it so that it accepts IP addresses in HEX format.

Is there some function to convert hex IP addresses to decimal?

War es hilfreich?

Lösung

I haven't tested this but should work.

#include <stdio.h>          /* stderr, stdout */
#include <netinet/in.h>     /* in_addr structure */
#include <strings.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char **argv) {

if ( argc == 2) {

  struct sockaddr_in sa;
  char a[2048] = {'\0'}; // placeholder    not to overflow and initialised.
  if( NULL == strchr(argv[1],'.') )
  {
      unsigned int unit0, uint1, uint2, uint3;
      sscanf(argv[1], "%2x%2x%2x%2x", &uint0, &uint1, &uint2, &uint3);
      sprintf(a,"%u.%u.%u.%u",uint0, uint1, uint2, uint3);
  }
  else
      strcpy(a.argv[1]);
  sa.sin_family = AF_INET;
  inet_pton(AF_INET, a, &sa.sin_addr);

  char node[NI_MAXHOST];
  int res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
  if (res)
  {
    printf("&#37;s\n", gai_strerror(res));
    return 1;
  }
  printf("%s\n", node);

  return 0;
 }
}

Thanks

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top