tags:

views:

25

answers:

2

I have written a small server

#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>

int main()
{
int server_fd, newsock_fd, server_len, newsock_len;
struct sockaddr_in server_struct, newsock_struct;

server_fd=socket(AF_INET,SOCK_STREAM,0);
server_struct.sin_family=AF_INET;
server_struct.sin_addr.s_addr=inet_addr("127.0.0.1");
server_struct.sin_port=htons(9734);
server_len=sizeof(server_struct);
newsock_len=server_len;

bind(server_fd,(struct sockaddr *)&server_struct,server_len);

listen(server_fd,5);

while(1)
{
printf("server waiting\n");
newsock_fd=accept(server_fd,(struct sockaddr *)&newsock_fd,&newsock_len);
char ch;
read(newsock_fd,&ch,1);
printf("got charachter %c\n",ch);
close(newsock_fd);
}
return 0;
}

When I am running it, the accept calls blocks initially, but after it creates the new socket it does not blocks for the second time. I am getting this type of output:-

server waiting <= blocks initially , started client
got charachter a <= correctly displays the charachetr
server waiting <= expected to be blocked again ????
got charachter a 
server waiting
got charachter a
server waiting

Am I missing something?

+3  A: 

This line here:

newsock_fd=accept(server_fd,(struct sockaddr *)&newsock_fd,&newsock_len);

is, shall we say, rather interesting.

Why do you give the address of your newsock_fd as the second parameter? That's just asking for trouble :-)

I think it should probably be:

newsock_fd = accept (server_fd, (struct sockaddr *)&newsock_struct, &newsock_len);
paxdiablo
It is a typo error. Thanks. Now it is working fine
Ashish
+1  A: 
int server_fd, newsock_fd, server_len, newsock_len;
struct sockaddr_in server_struct, newsock_struct;
/* ... */
newsock_fd=accept(server_fd,(struct sockaddr *)&newsock_fd,&newsock_len);

From accept(2):

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

You're passing a pointer to a file descriptor, not a struct sockaddr.

sarnold