Vikash Balasubramanian
Vikash Balasubramanian

Reputation: 3233

Weird Behaviour while reading sockets

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;
}

Upvotes: 0

Views: 65

Answers (1)

Vikash Balasubramanian
Vikash Balasubramanian

Reputation: 3233

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.

Upvotes: 1

Related Questions