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

nkcskrwz  于 2023-08-03  发布在  Unix
关注(0)|答案(1)|浏览(108)

当我传递一个无效的主机名时,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?

zd287kbt

zd287kbt1#

您应该检查gethostbyname的返回值。如果失败,当前程序将表现出未定义的行为,因为您取消了对空指针的引用。

相关问题