/***************************************************** name: socket example written by:1jjk E-mail:lingjiujianke@gmail.com compile: gcc -O2 -Wall -o server1 server1.c ******************************************************/ #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<time.h> #include<strings.h> #include<stdlib.h> #include<sys/utsname.h>
#define PORTNUM 3333 #define HOSTLEN 256 #define oops(msg) {perror(msg);exit(1);}
int main(int ac,char *av[]) { struct utsname uts; struct sockaddr_in saddr; struct hostent *hp; char hostname[HOSTLEN]; int sock_id,sock_fd; FILE *sock_fp; char *ctime(); time_t thetime;
sock_id=socket(PF_INET,SOCK_STREAM,0); if(sock_id==-1) { oops("socket"); }
bzero((void *)&saddr,sizeof(saddr)); gethostname(hostname,HOSTLEN); saddr.sin_addr.s_addr=htonl(INADDR_ANY); saddr.sin_port=htons(PORTNUM); saddr.sin_family=AF_INET;
if(bind(sock_id,(struct sockaddr *)&saddr,sizeof(saddr))!=0) oops("bind");
if(listen(sock_id,1)!=0) oops("listen");
while(1) { sock_fd=accept(sock_id,NULL,NULL); printf("got a call\n"); if(sock_fd==-1) oops("accept");
sock_fp=fdopen(sock_fd,"w"); if(sock_fp==NULL) oops("fdopen");
thetime=time(NULL);
fprintf(sock_fp,"the time is .."); fprintf(sock_fp,"%s\n",ctime(&thetime)); fprintf(sock_fp,"The server host name is %s\n",hostname); if(uname(&uts)==-1) { fprintf(sock_fp,"Unable to see the kernel\n "); fclose(sock_fp); } fprintf(sock_fp,"the OS is %s\n",uts.sysname); fprintf(sock_fp,"the kernel version is %s\n",uts.release); fclose(sock_fp); } }
|