views:

72

answers:

2

I am trying to use 'gethostbyname'. If I hardcode a host name directly into the function call it works great. However, I am trying to pass user input into this function. I believe my problem may because the array I am passing to the function has many trailing whitespaces.

  void connectHost(char *hostname)
    {

    int n;

    //This works
    //n = gethostbyname("irc.ubuntu.com");

    //This always returns NULL
    n = gethostbyname(hostname);

    if(n == NULL)
    {
    printf("Host Not Found.");
    }

    }

    int main()
    {
    char hostname[256];
    fgets(hostname,255,stdin);
    connectHost(hostname);
    } 

So what is the best way to just pass the host name to the function? Should I not be using fgets?

Thanks!

A: 

Whenever you input using fgets() remember to exclude the '\n':

fgets(hostname,255,stdin);
hostname[strlen(hostname)-1] = 0;
Donotalo
Note that `fgets` does not *always* contain a trailing newline (for example, if the line was truncated or if the last line in a file doesn't end in one).
jamesdlin
@jamesdlin: thanks. i actually provided simple answer that should fit OP's necessity. OP is taking input from `stdin` and having newline problem.
Donotalo
Using `stdin` makes it very likely that there will be a final newline, but it doesn't guarantee it (you could press the shell's EOF key combination).
jamesdlin
+2  A: 

When you enter irc.ubuntu.com as the input, it'll be stored in hostname as irc.ubuntu.com\n.
You need to remove the \n at the end of the string by overwriting it with the nul character as:

fgets(hostname,256,stdin);    
hostname[strlen(hostname)-1] = 0;

Note that the 2nd argument of fgets is maximum number of characters to be read (including the final null-character), so in your case you pass it 256 not 255.

codaddict