I'm working on a program using static libraries & sockets with a server, and I thought I had it implemented correctly. I went to have it reviewed, since it isn't due for a week. The instructor said my sockaddr's could go out of scope and that I needed "some type of storage that maps file descriptor to the sockaddr pointer". He put a comment by the two lines in 'mysock.c' where it apparently will go out of scope. He mentioned something about creating a static struct to hold the separate data???
Can someone point me in the right direction/show me what he means? here are my .h/.c files.
mysock.h
mysock.cCode:#ifndef MYSOCK_H #define MYSOCK_H int tcp_init_server( const int port ); int tcp_server_accept( const int sd ); int tcp_client( const int server_port, const char * host, int * sd ); int fdprintf( const int fd, char * fmt, ... ); int fdgets(char *s, int size, const int fd ); int fdclose( const int fd ); #endif
Thanks in advance!Code:#include<stdio.h> #include<stdlib.h> #include<string.h> /* for protobyname */ #include <netdb.h> /* for socket, bind */ #include <sys/types.h> #include <sys/socket.h> /* fd io */ #include <unistd.h> #include <stdarg.h> int tcp_init_server(const int port) { int proto_num = getprotobyname ( "tcp" )->p_proto; int sd; int rc; struct sockaddr_in serv; /* this goes out of scope */ sd = socket( PF_INET, SOCK_STREAM, proto_num ); if ( sd < 0 ) { exit(1); } /* * setup the sockaddr_in */ serv.sin_family = PF_INET; serv.sin_addr.s_addr = htonl ( INADDR_ANY ); serv.sin_port = htons ( port ); rc = bind( sd, (struct sockaddr *)&serv, sizeof(serv) ); if ( rc < 0 ) { exit(1); } rc = listen( sd, 10 ); return sd; } int tcp_server_accept(const int sd) { int sd2; struct sockaddr_in cli; /* this goes out of scope */ socklen_t cli_len = sizeof(cli); sd2 = accept( sd, (struct sockaddr *)&cli, &cli_len ); if ( sd2 <= 0 ) { exit(1); } return sd2; } /* * input: a file descriptor along with printf style format string * and arguements to match * output: processes the format string and arguments then writes the * data to the input file descriptor * return: the number of bytes written * * notes: hopefully getting identical behavior to do printf */ int fdprintf( const int fd, char * fmt, ... ) { char * buf = NULL; int bytes; va_list ap; va_start( ap, fmt ); /* get the number of bytes needed */ bytes = vsnprintf ( NULL, 0, fmt, ap ); /* its actually one short */ ++bytes; buf = ( char * ) malloc( sizeof(char) * ( bytes + 1 ) ); bytes = vsnprintf ( buf, bytes, fmt, ap ); /* write the data */ write ( fd, buf, bytes ); /* free the data and the va_list */ va_end( ap ); free ( buf ); return bytes; } int fdgets(char *s, int size, const int fd ) { int r = read(fd, s, size); s[r] = 0; return r; } int fdclose( const int fd ) { return close (fd); }



LinkBack URL
About LinkBacks


