Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netdb.h>
- #include <string.h>
- #include <errno.h>
- #include <unistd.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- void * client_service_thread(void*arg);
- int main(int argc, char **argv )
- {
- // sd is the server socket descriptor. csd is client socket descriptor
- int sd, csd, status, on , queueLenghth = 10;
- struct addrinfo request, *result, *p;
- struct sockaddr_ln clientaddr;
- //struct sockaddr_ln clientaddr;
- socklen_t addrlen;
- request. ai_flags = AI_PASSIVE; // use my IP
- request.ai_socktype = SOCK_STREAM; // want TCP/IP connection_based communication.
- request.ai_protocol = 0;
- request.ai_addrlen = 0;
- request.ai_addr = NULL;
- request.ai_canonname = NULL;
- request.ai_next = NULL;
- request.ai_family = AF_INET;// want to use IPV4 32 bit IP addrress
- // get ready to connect
- status = getaddrinfo(0,"4008",&request, &result );
- // result now points to addrinfo
- if (status != 0) {
- fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
- exit(EXIT_FAILURE);
- }
- for (p = result; p != NULL; p = p->ai_next) {
- sd = socket(result->ai_family, result->ai_socktype, result-> ai_protocol);
- if (sd == -1) {
- perror("socket");
- continue;
- }
- on = 1;
- // make port reusable by eliminating the adress already in use.
- if(setsockopt(sd, SOL_SOCKET, SO_REUSEADDR,&on,sizeof (on)) != 0) {
- perror("setsockopt");
- close(sd);
- continue;
- }
- // bind the descriptor to the address
- if (bind(sd, p->ai_addr,p->ai_addrlen) == -1) {
- close(sd);
- perror("server: bind");
- continue;
- }
- break;
- }
- freeaddrinfo(result);// free because we done using it
- if (p == NULL) {
- fprintf(stderr, "server: faiuled to bind\n");
- exit(1);
- }
- if (listen(sd,10) == -1){
- perror("listen");
- exit(1);
- }
- printf("server: waiting for connections...\n");
- addrlen = sizeof(clientaddr);
- while((csd = accept(sd,(struct sockaddr *)&clientaddr, &addrlen)) !=-1){
- pthread_t tid;
- int * csdptr;
- csdptr = malloc(sizeof(csd));
- *csdptr = csd;
- pthread_create(&tid,NULL, client_service_thread,csdptr);
- }
- if (csd){
- }
- }
- void * client_service_thread(void*arg){
- int csd;
- csd = *((int*)arg);
- free(arg);
- pthread_detach(pthread_self());
- }
Add Comment
Please, Sign In to add comment