2013-02-22 141 views
1

我正在使用UNIX套接字(作爲家庭作業的一部分)編寫HTTP客戶端。目前,我有這方面的工作代碼連接到指定的IP地址:獲取地址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文檔是非常殘酷的。

+0

'的#include '' – ugoren 2013-02-22 06:21:55

+3

memcpy的(&address.sin_addr,host_entity-> h_addr_list [0],host_entity->長度h_length);' – 2013-02-22 06:21:55

+0

@BrianRoach該做到了!如果你想把它寫成答案,我會接受它。 :) – Darthfett 2013-02-24 18:42:59

回答

2

你想要的是也許getaddrinfo(3)

 
#include 
#include 

static int 
resolve(const char *host, const char *port) 
{ 
     struct addrinfo *aires; 
     struct addrinfo hints = {0}; 
     int s = -1; 

     hints.ai_family = AF_UNSPEC; 
     hints.ai_socktype = SOCK_STREAM; 
     hints.ai_flags = 0; 
#if defined AI_ADDRCONFIG 
     hints.ai_flags |= AI_ADDRCONFIG; 
#endif /* AI_ADDRCONFIG */ 
#if defined AI_V4MAPPED 
     hints.ai_flags |= AI_V4MAPPED; 
#endif /* AI_V4MAPPED */ 
     hints.ai_protocol = 0; 

     if (getaddrinfo(host, port, &hints, &aires) < 0) { 
       goto out; 
     } 
     /* now try them all */ 
     for (const struct addrinfo *ai = aires; 
      ai != NULL && 
        ((s = socket(ai->ai_family, ai->ai_socktype, 0)) < 0 || 
         connect(s, ai->ai_addr, ai->ai_addrlen) < 0); 
      close(s), s = -1, ai = ai->ai_next); 

out: 
     freeaddrinfo(aires); 
     return s; 
} 

這個版本讓你從一個主機/端口對插槽。它還將主機和服務字符串的IP地址用於端口。但是,它已經連接到有問題的主機。