2013-02-22 1 views
1

주소 IP를 얻기 및 소켓을 사용하여 그것을 연결하는 (숙제의 일부로서). 나는 현재 주어진 IP 주소에 연결이 작동 코드를 가지고 : server_address는 또한 "google.com"와 같은 IP하지 뭔가를 할 수 있도록내가 UNIX 소켓을 사용하여 HTTP 클라이언트를 쓰고 있어요

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

그러나, 나는 지금 수정하려는. 나는 이것을 gethostbyname을 사용하여 수행하는 방법을 알아 내려고 노력했지만 문제가 있습니다.

IP 주소 또는 "google.com"와 같은 주소를 모두 수용으로 gethostbyname 의지와는 제대로 작동했다? (또는 나는 시도하고 첫 번째 주소에 정규식을 실행하고 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

+3

의 방어 적이기 (address.sin_addr, host_entity-> h_addr_list [0] host_entity-> h_length) 해냈다' –

+0

@BrianRoach! 그걸 대답으로 쓰고 싶다면 받아 들일 것입니다. :) – Darthfett

답변

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 주소가 필요합니다. 그러나 문제의 호스트에 이미 연결됩니다.