【问题标题】:Getting an address IP and using a socket to connect to it获取地址 IP 并使用套接字连接到它
【发布时间】:2013-02-07 16:58:45
【问题描述】:

我正在编写一个使用 UNIX 套接字的 HTTP 客户端(作为家庭作业的一部分)。我目前有这个工作代码来连接到给定的 IP 地址:

int sockfd = socket(AF_INET, SOCK_STREAM, 0);
char *server_address = "127.0.0.1";
struct sockaddr_in address;
if (sockfd < 0) {
    printf("Unable to open socket\n"); 
    exit(1);
}

// Try to connect to server_address on port PORT
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(server_address);
address.sin_port = htons(PORT);

if (connect(sockfd, (struct sockaddr*) &address, sizeof(address)) < 0) {
    printf("Unable to connect to host\n");
    exit(1);
}

但是,我现在想修改它,以便 server_address 也可以是不是 IP 的东西,例如“google.com”。我一直试图弄清楚如何使用gethostbyname 来做到这一点,但我遇到了麻烦。

gethostbyname 是否会同时接受 IP 地址或“google.com”之类的地址并使其正常工作?(或者我应该先尝试在该地址上运行正则表达式,然后再执行其他操作,如果它是一个 IP 地址)?

我已尝试使用以下代码尝试使其与“google.com”之类的内容一起使用,但我收到了警告warning: assignment makes integer from pointer without a cast

struct hostent *host_entity = gethostbyname(server_address);
address.sin_addr.s_addr = host_entity->h_addr_list[0];

我知道我做错了,但 gethostbyname 文档很糟糕。

【问题讨论】:

  • memcpy(&amp;address.sin_addr, host_entity-&gt;h_addr_list[0], host_entity-&gt;h_length);
  • @BrianRoach 做到了!如果你想把它写下来作为答案,我会接受。 :)

标签: c sockets gethostbyname


【解决方案1】:

你想要的可能是getaddrinfo(3):

#包括 #包括 静态整数 解决(常量字符*主机,常量字符*端口) { 结构 addrinfo *aires; 结构 addrinfo 提示 = {0}; 整数 s = -1; 提示.ai_family = AF_UNSPEC; 提示.ai_socktype = SOCK_STREAM; 提示.ai_flags = 0; #如果定义了 AI_ADDRCONFIG 提示.ai_flags |= AI_ADDRCONFIG; #endif /* AI_ADDRCONFIG */ #如果定义了 AI_V4MAPPED 提示.ai_flags |= AI_V4MAPPED; #endif /* AI_V4MAPPED */ 提示.ai_protocol = 0; if (getaddrinfo(host, port, &hints, &aires) ai_family, ai->ai_socktype, 0)) ai_addr,ai->ai_addrlen)ai_next); 出去: freeaddrinfo(aires); 返回 s; }

此版本为您提供来自主机/端口对的套接字。它还采用 IP 地址作为主机和服务字符串作为端口。但是,它已经连接到有问题的主机。

【讨论】:

    猜你喜欢
    • 2012-07-05
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    相关资源
    最近更新 更多