使用getnameinfo()解析以十六进制格式给出的IP地址

时间:2014-05-15 11:30:08

标签: c network-programming ip

我在C中有一个简单的程序,它将IP地址解析为主机名。

#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;
 }
}

它工作正常(即./a.out 10.1.1.2)但我需要修改它以便它接受HEX格式的IP地址。

是否有一些函数可以将十六进制IP地址转换为十进制?

1 个答案:

答案 0 :(得分:2)

我没有对此进行测试,但应该可以使用。

#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;
 }
}

由于

相关问题