Chinaunix首页 | 论坛 | 博客
  • 博客访问: 574974
  • 博文数量: 99
  • 博客积分: 3976
  • 博客等级: 中校
  • 技术积分: 1041
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-15 15:48
文章分类
文章存档

2009年(1)

2008年(5)

2007年(31)

2006年(58)

2005年(4)

分类: C/C++

2007-03-06 20:02:40

/*****************************************************
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);
    }
}

阅读(1765) | 评论(1) | 转发(1) |
给主人留下些什么吧!~~