Socket Programming- TCP server

11 12 2007

A Server Side TCP implementation c code 1.0

int main(void)
{
//1.Declare
int sockfd;
struct sockaddr_in my_addr; // my address information
struct sockaddr_in their_addr; // connector’s address information
int addr_len, numbytes;
char buf[MAXBUFLEN];

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror(“socket”);
exit(1);
}

//2. Set
my_addr.sin_family = AF_INET; // host byte order
my_addr.sin_port = htons(MYPORT); // short, network byte order
my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
memset(&(my_addr.sin_zero), ”,8);

//3. Bind
if (bind(sockfd, (struct sockaddr *)&my_addr,sizeof(struct sockaddr)) == -1) {
perror(“bind”);
exit(1);
}

//4.Listen
int status = listen(sockfd, 5);

//5.Accepting Connections


socklen_t sin_size = sizeof(struct sockaddr);
int ctr=0;

while(ctr<3)
{
printf(“waiting for clients\n”);
int new_fd = accept(sockfd,(struct sockaddr*)&their_addr,&sin_size);
printf(“connceted…\n”);
pthread_t t;

//Receiving Clients and handling them
pthread_create(&t,NULL,Handler,(void*)new_fd);

ctr++;
}

//Closing Socket

close(sockfd);
return 0;

}

Advertisements

Actions

Information

One response

12 12 2007
ali

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: