开发者

Problems when debugging a socket-using program in C: connect

I'm writting a simple client-server system using unix sockets. When executed from a terminal, my Client program creats a segmentation fault.

I'm quite sure that seg-fault is caused by some noob error, but my problem comes when I try to debug it using KDBG (kde gdb frontend).

This is where it breaks:

 if (DEBUG) printf("-- connect()... \n");
 if (connect (mySocket, (struct sockaddr *)socketAddr,sizeof (*socketAddr)) == -1) {
  perror(error);
  printf("%s\n",error);
  printf ("-- Error when stablishing a connection\n");
  return -1;
 }
开发者_StackOverflow

And this is the output:

-- connect()... 
Connection refused

-- Error when stablishing a connection

Can't I debug this code that way? Why?

If I should can, do you now what's hapenning there? What should i do in order to get more information?

PS: PS: @abelenky: that part works perfect out of the debugger. This is the declaration of socketAddr:

struct sockaddr_in socketAddr; 

... 

if ( (mySocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    printf("Error al crear el socket\n"); 
    return -2; 
}


These functions expect a string and you are passing them something else.

For example:

perror("socket");

Although I don't know from your code where error is declared... Perhaps you are thinking of the global variable errno, which is in integer?

By the way, perror is roughly equivalent to this:

void perror(const char *str)
{
    fprintf(stderr, "%s: %s\n", str, strerror(errno));
}

Update based on comments:

In that case my guess is you haven't intiailized error to anything... I am not sure what you are expecting to be in error, but for example you might want to try something:

snprintf(error, sizeof(error), "Error in %s:%d\n", __FILE__, __LINE__);
perror(error);

Update 2:

I think you want this:

if (connect (mySocket, (struct sockaddr *)&socketAddr, sizeof (socketAddr)) == -1) {

Note that I have added a & before socketAddr and removed the * from the sizeof.

How are you doing hostname lookups? I recommend getaddrinfo, eg.:

struct addrinfo *res = NULL, hint;
char service[32];
int error;

snprintf(service, sizeof(service), "%d", port);

memset(&hint, 0, sizeof(hint));
hint.ai_socktype = SOCK_STREAM;

if ((error = getaddrinfo(host, service, &hint, &res)))
{
   fprintf(stderr, "No se pudo encontrar %s: %s\n", host, gai_strerror(error));
}
else
{
   fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
   if (fd < 0)
   {
      perror("Error al crear el socket");
   }
   else if (connect(fd, res->ai_addr, res->ai_addrlen))
   {
      perror("Error al conexionar con el servidor");
      close(fd);
      fd = -1;
   }
}

if (res)
{
   freeaddrinfo(res);
}

This will let you get a sockaddr from a hostname and port without caring about IPv4, IPv6, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜