Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C unix socket programming, connect() hanging on invalid host name

I'm having a hanging issue with the connect function when I pass an invalid host name.

#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() is hanging if I give an invalid host name as an argument. If I give a valid host name everything works according to plan. A valid host name but invalid port will go to return 0. My question is, why is it hanging and not returning -1 when I give an invalid host name?

Thanks for any help

like image 438
pandaEater Avatar asked Nov 05 '22 07:11

pandaEater


1 Answers

You should be checking the return value from gethostbyname. If it fails, your current program exhibits undefined behavior because you're dereferencing a null pointer.

like image 145
Fred Foo Avatar answered Nov 09 '22 06:11

Fred Foo