I don't know where I have to put my close():
my code is like this:
Code:
#define SOCKET_ERROR -1
#define STRGLEN 100 /* message string length */
const int APORT = 1234; /* port number */
/* Function main */
main(){
int fromlen;
char hostname[64]; /* local machine hostname */
struct hostent *hp; /* gethostbyname return ptr */
register int s; /* socket descriptor, or -1 if error */
register int ns; /* created new socket for accept */
struct sockaddr_in sin; /* socket structure */
struct sockaddr_in fsin; /* socket str. for accept*/
int p1;
/* first need to know our hostname. */
gethostname(hostname, sizeof(hostname));
/* Next look up the network address of our host.*/
if((hp = gethostbyname(hostname)) == NULL){
fprintf(stderr, "%s: unknown host\n", hostname);
exit(-1);
}
/* create socket in Internet domain(AF_INET), that is
connection oriented (SOCK_STREAM) rather than
connectionless (SOCK_DGRAM),
arg3=0 for default TCP/IP protocol*/
if(( s = socket(AF_INET, SOCK_STREAM, 0) ) < 0){
perror("server: socket");
exit(-1);
}
/* Create the address to connecting to. We use port
APORT but put it into network byte order.
Also we use bcopy to copy the network number. */
bzero(&sin, sizeof(sin));
sin.sin_family = AF_INET; /* IP protocol */
/* sin.sin_addr.s_addr = INADDR_ANY;*/
sin.sin_port = htons(APORT);
bcopy(hp->h_addr, &sin.sin_addr, hp->h_length);
/* Try to bind(address and port no.)to socket s */
if(bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0){
perror("server: bind");
exit(-1);
}
/* server ready, listen on socket s max 2 requests queued*/
if(listen(s, 2) < 0) {
perror("server: listen");
exit(-1);
}
/* Accept connections then fork ns (new socket) that
will be connected to the client. fsin will contain
the IP address of the client. */
bzero(&fsin, sizeof(fsin));
fromlen = sizeof(fsin);
if((ns = accept(s, (struct sockaddr *)&fsin, &fromlen))<0){
perror("server: accept");
exit(-1);
}
if((p1 = fork()) > 0){
server(ns);
}
else{ /* child */
server(ns);
}
}
do I put my close(s) in the if, else, or elsewhere?