linux - c server handle multiple connections, error on port no -
i've been experimenting server code http://www.linuxhowtos.org/c_c++/socket.htm.
the regular server code worked fine, i've changed hardcode in port number rather read command line, wanted server capable of holding multiple connections. waiting short strings come in 3 different client programs @ regular intervals.
i've compiled below i'm getting error "error, no port provided", makes no sense i've included port number.
some initial questions
- does have idea wrong?
- also, hope no 1 minds me asking question, adapted use multi-threading?
i'm using dual core mini-processor centos. needs read short amounts of data socket, passed @ regular intervals. i'm aware forking overload cpu , multi-threading may memory intensive type of machine.
are there other alternatives handling multiple socket connections worth me researching? data come in every 5 seconds, every few hours, twice day respectively.
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> void read_socket(int); /* function prototype */ void error(const char *msg) { perror(msg); exit(1); } int main(int argc, char *argv[]){ int store_limit=10; //user input int store_limit_secs=store_limit * 24 * 60 * 60; //user input int sockfd, newsockfd, portno, pid; socklen_t clilen; struct sockaddr_in serv_addr, cli_addr; if (argc < 2) { fprintf(stderr,"error, no port provided\n"); exit(1); } sockfd = socket(af_inet, sock_stream, 0); if (sockfd < 0) error("error opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = 15000; serv_addr.sin_family = af_inet; serv_addr.sin_addr.s_addr = inaddr_any; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("error on binding"); listen(sockfd,5); clilen = sizeof(cli_addr); while (1) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("error on accept"); pid = fork(); if (pid < 0) error("error on fork"); if (pid == 0) { close(sockfd); read_socket(newsockfd); exit(0); } else close(newsockfd); } /* end of while */ close(sockfd); return 0; /* never here */ } void read_socket (int sock) { int n; char buffer[256]; bzero(buffer,256); n = read(sock,buffer,255); if (n < 0) error("error reading socket"); printf("here message: %s\n",buffer); n = write(sock,"i got message",18); if (n < 0) error("error writing socket"); }
in absence of command-line argument, argc
1
, block execute, resulting program exiting:
if (argc < 2) { fprintf(stderr,"error, no port provided\n"); exit(1); }
since hardcoded value portno
, can remove block.
Comments
Post a Comment