nslooup.c无法处理http / https?

时间:2018-05-01 23:03:56

标签: c ubuntu tcp

我试图在udp / tcp c编程中完成我的第一步,并且我遇到了问题。 在编译并运行nslookup.c之后(我使用的是Linux Ubuntu)我已经收到了网络信息,只要我没有在域名之前输入协议。 例如,输入./nslookup www.yahoo.com - 可以正常工作。 但是,输入./nslookup http://www.yahoo.com - 会导致错误:Error in resolving hostname

这是我使用的代码:

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char* argv[]) {
  struct addrinfo* res;
  char* hostname;
  char* hostaddr;
  struct sockaddr_in* saddr;

  if (argc != 2) {
    perror("Usage: hostnamelookup <hostname>\n");
    exit(1);
  }

  hostname = argv[1];

  if (0 != getaddrinfo(hostname, NULL, NULL, &res)) {
    fprintf(stderr, "Error in resolving hostname %s\n", hostname);
    exit(1);
  }

  saddr = (struct sockaddr_in*)res->ai_addr;
  hostaddr = inet_ntoa(saddr->sin_addr);

  printf("Address for %s is %s\n", hostname, hostaddr);
  exit(0);
}

这个问题的原因是什么? 感谢

1 个答案:

答案 0 :(得分:0)

http://www.yahoo.com不是主机名,而是网址。一个网址 有(或可能有)几个组件,但在这种情况下,它 只是一个协议(&#39; http&#39;部分和主机名,即 www.yahoo.com部分。所以,那部分,是一个真正的主机名 将(或可能,可能有其他错误)得到解决, 而url,不是主机名,将失败。你可能需要 如果你需要做这种事情,写或使用url解析器 更一般地说。