C unix socket编程,connect()挂在无效的主机名上

时间:2012-01-18 19:31:00

标签: c sockets network-programming connect hang

当我传递无效的主机名时,我遇到了connect函数的问题。

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define ERROR_NUM           -1
#define BUFFER_SIZE         500
#define HOST_NAME_SIZE      255
#define MY_ID       5

int  main(int argc, char* argv[])
{
int hSocket;                 /* handle to socket */
struct hostent* pHostInfo;   /* holds info about a machine */
struct sockaddr_in Address;  /* Internet socket address stuct */
long nHostAddress;
char pBuffer[BUFFER_SIZE];
char userName[BUFFER_SIZE];
char hostName[HOST_NAME_SIZE];

if(argc < 2){
    printf("\nUsage: username@hostname\n");
    return 0;
}
else{
    int i = 0;
    int length;
    if((length = strlen(argv[1])) >= BUFFER_SIZE){
        printf("Argument entered is too long\n");
        return 0;
    }
    while(*(argv[1] + i) != '@'){
        ++i;
        if(i >= length){
            printf("Usage: username@hostname\n");
            return 0;
        }
    }
    strncpy(userName, argv[1], i);
    argv[1]+=(i+1);
    strcpy(hostName,argv[1]);
}

printf("\nMaking a socket\n");
if((hSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == ERROR_NUM){
    printf("\nCould not make a socket\n");
    return 0;
}

/* get IP address from name */
pHostInfo=gethostbyname(hostName);
if(!pHostInfo){
    printf("Could not resolve host name\n");
    return 0;
}
/* copy address into long */
memset(&nHostAddress, 0, sizeof(nHostAddress));
memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);

/* fill address struct */
Address.sin_addr.s_addr=nHostAddress;
Address.sin_family=AF_INET;
/* finding host port num */
int x = 5000 + (MY_ID-1)* 10;
int y = 5000 + (MY_ID*10) - 1;
for(x; x <= y; ++x){
    Address.sin_port=htons(x);
    if(connect(hSocket,(struct sockaddr*)&Address,sizeof(Address)) > ERROR_NUM){
        break;
    }
}
if(x > y){
    printf("\nFailed to connect to host port\n");
    return 0;
}
printf("\nConnected to %s on port %d\n", hostName, x);
printf("Client closing socket\n\n");                    
if(close(hSocket) == ERROR_NUM){
    printf("\nCould not close socket\n");
    return 0;
}
如果我将无效的主机名作为参数,则

connect()挂起。如果我提供有效的主机名,一切都按计划进行。一个有效的主机名但无效的端口将返回0.我的问题是,当我给出一个无效的主机名时,为什么它挂起并且不返回-1?

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您应该检查gethostbyname的返回值。如果失败,则当前程序显示未定义的行为,因为您正在取消引用空指针。