0

I am trying a basic client server program. I need my server to get the ip address of the client. The following lines in my server code does this

SNIPPET 1

struct sockaddr_in* laddr=malloc(sizeof(struct sockaddr_in));

socklen_t len;
int accepted_fd = accept(sockfd,(struct sockaddr*)laddr,&len);

char* ip = malloc(20);
inet_ntop(AF_INET,&(laddr->sin_addr), ip,20);

This works perfectly and i get the correct ip address of client.

But, if i add the following two lines below to read data from client

SNIPPET 2

struct message* m=(struct message*)malloc(sizeof(struct message));
int num_bytes = read(accepted_fd,m,sizeof(struct message));

then the ip is read as zero. I mean adding SNIPPET 2 below SNIPPET 1 somehow changes the working of SNIPPET 1.

can someone please explain what's happening? Thanks.

EDIT 1

Here is the entire main function for server

int main(int argc,char* argv[])
{
  if(argc!=2)
  {
   printf("Error port number missing\n");
   exit(-1);
  }

  char* relay_server_port = argv[1];

  int sockfd = socket(AF_INET,SOCK_STREAM,0);

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(atoi(relay_server_port));
  addr.sin_addr.s_addr = INADDR_ANY; 

  int success = bind(sockfd,(const struct sockaddr*)&addr,sizeof(addr));

  success = listen(sockfd,4);

  while(1)
 {
   struct sockaddr_in* laddr=malloc(sizeof(struct sockaddr_in));

   socklen_t len;

   int accepted_fd = accept(sockfd,(struct sockaddr*)laddr,&len);

   char* ip = malloc(20);
   inet_ntop(AF_INET,&(laddr->sin_addr), ip,20);
   printf("%s\n",ip);

   struct message* m=(struct message*)malloc(sizeof(struct message));
   int num_bytes = read(accepted_fd,m,sizeof(struct message));
   close(accepted_fd);
 }
return 0;
}
Vikash Balasubramanian
  • 2,921
  • 3
  • 33
  • 74
  • 2
    1. [You don't need to cast `malloc()`](http://stackoverflow.com/a/605858/1983495), 2. The code is not enough, and it's also unsef to ignore the return value of `malloc()` in both cases, I know that it would not cause the current behavior of your program, but you should always write safe code, so more code is needed, probably the whole function. – Iharob Al Asimi Mar 09 '15 at 17:10
  • 1
    you keep mallocing without freeing, up to a point it will explode. if `struct message` is huge, it may accelerate the explosion. – Jason Hu Mar 09 '15 at 17:37
  • I know, and i will rectify it , but the moment i saw this weird problem i stopped coding further, and obviously my program isn't complete. – Vikash Balasubramanian Mar 09 '15 at 17:45

1 Answers1

1

I figured it out. I had to intialize the value of len to that of the size of the sockaddr_in structure i.e. it is a value result argument.

alk
  • 69,737
  • 10
  • 105
  • 255
Vikash Balasubramanian
  • 2,921
  • 3
  • 33
  • 74