----- Original Message -----
From: "Ahmed Shabana" <[email protected]>
To: <[email protected]>
Sent: Tuesday, January 20, 2009 11:14 AM
Subject: [c-prog] socket() ; SUCCESS but !!!
> This server code runs well at its first run
> but when I run it again it give me error in bind()
>
> #include<stdio.h>
> #include<string.h>
> #include<unistd.h>
> #include<stdlib.h>
> #include<sys/socket.h>
> #include<netdb.h>
>
> #define SERVER_ERROR(msg,exit_code) \
> do { fprintf(stderr,msg);exit(exit_code);}while(0)
> #define BUF_SIZE 500
>
> // This code will represent a simple server that can response to any
> http request and load simple module called "MYMOD"
> // This will take two args $ $PROGRAM_NAME SOCKET_NUMBER
> int main( int argc, char* argv[])
> {
> int sfd;
> char msg[100];
> struct addrinfo hints,*res;
>
> if ( argc != 2){
> sprintf(msg,"USAGE: $%s PortNumber \n",argv[0]);
> SERVER_ERROR(msg,100);
> }
> // Create addr info data to use in socket() Creation
> hints.ai_family = AF_UNSPEC;
> hints.ai_socktype = SOCK_STREAM;
> hints.ai_protocol = 0;
> if ( getaddrinfo("localhost", "1111" ,&hints ,&res) )
> SERVER_ERROR("getaddrinfo",99);
> if ( (sfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol))
> == -1 )
> SERVER_ERROR("socket()",101);
> if ( bind(sfd, res->ai_addr, res->ai_addrlen) )
> SERVER_ERROR("bind()",102);
> freeaddrinfo(res);
> if ( listen(sfd ,5) )
> SERVER_ERROR("listen()",103);
>
> struct sockaddr_in cs;
> socklen_t slen;
> puts("WE ARE LISTENING NOW .....");
> if (accept(sfd ,&cs ,&slen) == -1)
> SERVER_ERROR("accept()",104);
> puts("Client trying to connect now ...");
> close(sfd);
> return 0;
> }
I don't know but is this off topic for this mailing list? I'm as
interested as the next guy in posix networking and threads but I thought
this group was about *standard* C and C++.
Bill