segmentation fault in linux (socket programming (TCP) in C)

user

I am just learning socket programming on Linux by some websites and here are some parts of my code on server side by using TCP:

#define BufferLength 100
#define SERVPORT 3111
int main()
{
  /* Variable and structure definitions. */
  int sd, sd2, rc, length = sizeof(int);
  int totalcnt = 0, on = 1;
  char temp;
  char buffer[BufferLength];
  struct sockaddr_in serveraddr;
  struct sockaddr_in their_addr;
  fd_set read_fd;

  /* Get a socket descriptor */
  if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  {
    perror("Server-socket() error");
    exit (-1);
  }
  else
    printf("Server-socket() is OK\n");

  /* Allow socket descriptor to be reusable */
  if((rc = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) < 0)
  {
    perror("Server-setsockopt() error");
    close(sd);
    exit (-1);
  }
  else
    printf("Server-setsockopt() is OK\n");

  /* bind to an address */
  memset(&serveraddr, 0x00, sizeof(struct sockaddr_in));
  serveraddr.sin_family = AF_INET;
  serveraddr.sin_port = htons(SERVPORT);
  serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
  printf("Using %s, listening at %d\n", inet_ntoa(serveraddr.sin_addr), SERVPORT);

  /* continue */
}

When I did the last line (printf("using......")), I got a segmentation fault, why? Thanks.

alk

The code as shown misses to #include any headers, so as it stands won't compile due to some undefined symbols.

It would compile however if you missed to just prototype any library functions referenced by the code, which would lead to any function being assumed to return int.

The latter fact might be fatal or not.

On a 64bit system at least it is fatal in the case of inet_ntoa() used as a parameter to printf(), as on a 64bit system it most likely is expected to return a 64bit (char-pointer) value (but a 32bit int). So (assuming the prototype misses) when generating the code the compilers assumes inet_ntoa() to return a 32bit int which would lead to "chopping-off" the most significant 32bits of the address returned. Trying to printf() from such a "crippled" and therefore (most likely) invalid address provokes undefined behaviour and in your case leads to the segmentation violation observed.

To fix this, add the relevant prototype (for inet_ntoa()) by adding:

#include <arpa/inet.h>

The compiler should have warned you about this. To enable all compiler's warnings for gcc use the options -Wall -Wextra -pedantic. Take such warnings serious.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related