Chinaunix首页 | 论坛 | 博客
  • 博客访问: 375824
  • 博文数量: 62
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 557
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-01 14:04
文章分类

全部博文(62)

文章存档

2014年(1)

2013年(61)

分类: C/C++

2013-11-17 19:35:38

原文地址:socket例子实现 作者:1jjk

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

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