We help IT Professionals succeed at work.

help with gethostbyname function in C

headachebr
headachebr asked
on
1,278 Views
Last Modified: 2008-08-06
I am trying to connect to a server that I create. My server works fine if the client is in the same host because I use this in the client code:

Code:

serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

Now, when I try to connect to the server, being in a different host, I do this:
Code:

struct hostent *he;
..

char *servername = argv[1];
he = gethostbyname(servername);
memcpy(&serverAddr.sin_addr, he->h_addr_list[0], he->h_length);
      
// Connecting to the server
puts("1");
if (connect(mySock, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {
      puts("2");
        perror("connect");
        return EXIT_FAILURE;
}
puts("Connected to the server.");

The problem is that the "1" gets printed, and the "Connected..." message never appears.. So it gets stuck in connect. I am 100% sure it's something wrong with that gethostbyname, I must be using it wrong.

Can anyone enlighten me?
Comment
Watch Question

Commented:
try this:  I think the memcpy part was a little off..

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>


int main(int argc, char *argv[] )
{
      int mySock;
      struct hostent *he;
      socklen_t socklen = sizeof(struct sockaddr_in);      
      struct sockaddr_in  serverAddr;
      
      serverAddr.sin_port = htons( 80 );
      serverAddr.sin_family = AF_INET;
      
      he = gethostbyname("www.hotmail.com");
      if( !he )
      {
            printf("no go on gethostbyname! try again!\n");
            exit(-1);
      }
      
      //memcpy(&serverAddr.sin_addr, he->h_addr_list[0], he->h_length);
      memcpy ( &serverAddr.sin_addr.s_addr,
                   he->h_addr_list[0],
                   he->h_length );
      
      mySock = socket(AF_INET, SOCK_STREAM, 0 );
      // Connecting to the server
      puts("1");
      if (connect(mySock, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) {
            puts("2");
                  perror("connect");
                  return EXIT_FAILURE;
      }
      puts("Connected to the server.");
      
      close( mySock );
      
      return 0;
}

Author

Commented:
Still nothing...

This is not goooood...! =\

Author

Commented:
I have also tried:

bcopy(he->h_addr, &serverAddr.sin_addr, he->h_length);

and nothing either =\

Commented:
in the copy, it's supposed to be:

&serverAddr.sin_addr.s_addr

not

&serverAddr.sin_addr

the other thing to look at is the return value of gethostbyname.. .is it null?
and print out the hostent structure something like this:

for( i = 0; i < sizeof(struct hostent); i++ )
{
    printf( "%02x ", *((char *) he+i) );
}
if it is all zeros.. well that would be a problem..

I actually compiled and ran that code up there successfully on linux with no problem.. I cut and pasted it exactly from my test file..

if you're on windows don't forget the WSAStartup stuff..

Commented:
also make sure the port you are using is open on the destination address..

if you are unsure, try to telnet to the port with:

telnet hostname port

Commented:
also ping the host to make sure you can see it on the network

Author

Commented:
I did the telnet deal and I just got this:
Trying 128.8.10.152...
Just like my client does.. lol
I changed port numbers to see what happened and same thing happened.
Ports that I am using are way above 2000 by the way. =)

I printed out to see what sin_addr was set to and the result was the correct server IP.
So maybe there is a problem with my server.c? I am running on my school Linux machine.

Bind and Listen on the server code don't return an error, so those lines come after


		puts("Server is listening...");
 
		int csocket;
 
		unsigned int sin_size = sizeof(clientAddr);
		csocket = accept(servSock, (struct sockaddr *)&clientAddr, &sin_size);
 
		if (csocket == -1) {
			perror("accept");
			return EXIT_FAILURE; 
		}
		puts("Accepted connection from client.");

Open in new window

CERTIFIED EXPERT
Top Expert 2006

Commented:
>I did the telnet deal and I just got this:
>Trying 128.8.10.152...

This strongly suggests that there is an intervening firewall etc that is blocking the connection ... this could be a firewall on the server machine or in case you are connecting to a different network, it could be a router/gateway.

Commented:
my guess is a firewall issue if you are using a public network..

my recommendation is to test client independently of server

when testing the client:
use a known working server.. so in my example, I used www.hotmail.com
and port 80
you could send an HTTP GET request to hotmail and then receive the text in a response and print it to prove out the client side..

later, you could run the server on your pc (make sure the firewall allows that port), then run the client from your school linux box.. to connect back to your pc

Commented:
so.. what are you studying at the University of Maryland...

I think you've just about gotten this problem wrapped up.

Author

Commented:
Computer Science =)

jrocnuck, it's not a firewall issue, since we are supposed to be doing this on that server.
And I can't test it on my machine because I don't have Lunix.

The other thing is that if my client.c is on the same server as the server.c
and I use servAddr.sin_addr.s_addr = htonl(INADDR_ANY) for the client, everything works wonders!

I am able to transfer mp3s, images, txts, everything. But if I add that gethost and everything, it does that hanging... =(

Maybe both my port options where having issues? That would be just plan luck eh?
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
scary:~/project6/clientf: telnet <edited hostname> 22
Trying <edited IP1>...
Connected to <edited hostname>
Escape character is '^]'.
SSH-2.0-OpenSSH_4.4

Thats what I got, now the netstat part I did without running my program, but I saw my IP and the port 22 (which is prolly when I did the telnet on 22)
tcp        0      0 <edited IP1>:22             <edited IP2>:52297          ES

I am going to try with a higher ip... I was testing at 2212, imma try 30000ish
Going to bed right now, I see you in the morning! =)

Author

Commented:
Other port didn't work either...

I will check whats going on tomorrow. This is not fun when all I have left is this silly thing =(

Commented:
ok... btw.. might want to not show too much private information...

also a tip for rising CS majors.. burn off a copy of DVD bootable Knoppix when you get a chance...
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> now the netstat part I did without running my program

You should do it after starting the server ;) And see if the server port is in LISTENING state. Then once more when the client tries to connect ...

Btw, as jrocnuck said : you might want to hide those IP addresses etc. You can ask a moderator to remove them.

Author

Commented:
I am waiting for the teacher assistant here in the lab today to see if he knows what's going on...

Sorry about the IPs, I didn't know IPs where that important.. hee hee xD

>> tip for rising CS majors.. burn off a copy of DVD bootable Knoppix when you get a chance
what you mean? =P

I did the netstat while my program was running and it didn't display it as LISTENING at all... =(

Author

Commented:
Okay, I found out today that we are not supposed to do a cross server connection at the moment, because there exists a filewall between them...

I feel dumb at the moment... lol
But I will give you the kudos, since you were right! =)

Thanks again for the help!

Commented:
man.. I did all that work, and recommended checking for a firewall.. (posting at the same time as the other answer) and my answers didn't get accepted...   all the tests I mentioned were to prove that a firewall was blocking your port...

that's fairly dissappointing considering I spent a bit of time on this.. ...

Knoppix is a bootable full blown version of linux that can be burned onto a DVD or CD...
http://www.knoppix.net/

you can boot up on that when you need access to linux on a pc that doesn't have linux installed.


CERTIFIED EXPERT
Top Expert 2006

Commented:
I too feel that jrocnuck deserved credit for having suggested the correct diagnostic test.

headachebr, would you like to change question disposition and split the points?
https://www.experts-exchange.com/help.jsp#hi332

Author

Commented:
Oh geez... I sent to the wrong guy! =O

I am soooo sorry, I didn't see that!
jrocnuck, I did felt that you deserved the points, duh! =)

I will try to fix that...

Author

Commented:
Thank you sunnycoder =)
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.