Link to home
Start Free TrialLog in
Avatar of ngcl9681
ngcl9681

asked on

How to prevent connect() function from core dumping?

I'm trying to write a sockets client to access a remote server. The client program is on Red-Hat Linux Release 6.2 (kernel 2.2.14-5.0smp on an i686). If I enter a non existent ip address to connect to, the connect function core dumps. I want the connect program to accept any address.
How do I prevent this from happening and instead trap the error properly?

my code is something like:
..
        clnt.sin_family = AF_INET;
        clnt.sin_port = htons (5555);
        clnt.sin_addr.s_addr = inet_network("1.1.11.101");
        printf("addr = %s\n",inet_ntoa(clnt.sin_addr)); /* just check the address */

       if (connect(sock, (struct sockaddr *) &clnt, sizeof (clnt)) < 0)
         {
           perror ("connect error");
           return -1;
         }

ASKER CERTIFIED SOLUTION
Avatar of newmang
newmang

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> inet_ntoa(clnt.sin_addr)
should this be
  inet_ntoa(clnt.sin_addr.s_addr)
Avatar of BlackDiamond
BlackDiamond

ahoffmann,
inet_ntoa(clnt.sin_addr)  is correct.  clnt.sin_addr is a struct in_addr, which is the correct parameter for inet_ntoa.

ngcl,
I would recommend changing the following line due to byte ording issues:
   clnt.sin_addr.s_addr = inet_network("1.1.11.101");
to:
   inet_aton("1.1.11.101", &clnt.sin_addr);

This is because inet_network returns a long Host Byte Order, and you actually need it to be in network byte order for the assignment.  You could also accomplish the same thing with the following line (just for clarity), however, it is less efficient than the other example I gave you.

   clnt.sin_addr.s_addr = htonl(inet_network("1.1.11.101"));

Not sure why the core dump is happeneing though, but still looking.  Can you show us the code you are using to create the socket?


Avatar of ngcl9681

ASKER

Both newmanq and BlackDiamond are correct. The actual cause was not the connect() statement. Upon further investigation, I discovered that the return value of -1 was put into the list of sockets for a select statement. This was the actual cause of the dump.
How can I award the points for the answer? Can I click accept as answer twice or give to the first correct answer. I was not able to accept it earlier as I needed time to go through my code. Is there a way to share points? BlackDiamond's tip on the ip addressing is really helpful to improve the clarity of my program.
I am glad the infomation was helpful.

As far as spiltting points, you can etiher post a new message with more points, or post a message in the community support area asking a moderator to split the points up for you.