Chinaunix首页 | 论坛 | 博客
  • 博客访问: 131007
  • 博文数量: 19
  • 博客积分: 1188
  • 博客等级: 中尉
  • 技术积分: 210
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-12 01:16
文章分类

全部博文(19)

文章存档

2011年(1)

2010年(18)

分类: LINUX

2010-06-23 19:08:01

/*client.c*/
#include
#include
#include
#include
#include
#include
#include
#include
#include

#define PORT 3490
#define MAXDATASIZE 20

int main(int argc, char* argv[])
{
    int sockfd,numbytes;
    char buf[MAXDATASIZE];
    struct hostent *he;
    struct sockaddr_in ser_addr;

    if(argc != 2)
    {
        fprintf(stderr, "usage:client hostname\n");
        exit(1);
    }

    if((he=gethostbyname(argv[1])) == NULL)
    {
        herror("gethostbyname");
        exit(1);
    }

    if((sockfd=socket(AF_INET, SOCK_STREAM,0)) == -1)
    {
        perror("socket");
        exit(1);
    }

    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(PORT);
    ser_addr.sin_addr = *((struct in_addr*)he->h_addr);
    /* ser_addr.sin_addr.s_addr = inet_addr("192.168.17.101");
       */
   
    if(-1 == (connect(sockfd, (struct sockaddr*)&ser_addr, sizeof(struct sockaddr))))
    {
        perror("connect ");
        exit(1);
    }

    printf("connect sucess");

    if(-1 == (numbytes=recv(sockfd,buf,MAXDATASIZE,0)))
    {
        perror("recv");
        exit(1);
     }

     buf[numbytes] = '\0';
     printf("received: %s\n", buf);
     close(sockfd);

     return 0;
 }

/*server.c*/
#include
#include
#include
#include
#include
#include
#include
#include

#define MYPORT 3490
#define BACKLOG 10

int main(int argc, char *argv[])
{
    int sockfd, new_fd;
    struct sockaddr_in my_addr;
    struct sockaddr_in client_addr;
    int sin_size;

    if(-1 == (sockfd=socket(AF_INET, SOCK_STREAM, 0)))
    {
        perror("socket");
        exit(1);
    }
   
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(MYPORT);
    /* my_addr.sin_addr.s_addr = inet_addr("192.168.17.101"); */
    my_addr.sin_addr.s_addr = INADDR_ANY; /*auto-fill with my IP */

    if(-1 == bind(sockfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)))
    {
        perror("bind");
        exit(1);
    }

    if(-1 == listen(sockfd, BACKLOG))
    {
        perror("listen");
        exit(1);
    }

    while(1)
    {
        sin_size = sizeof(struct sockaddr_in);
        if(-1 == (new_fd=accept(sockfd,(struct sockaddr*)&client_addr, &sin_size)))
        {
            perror("accept");
            continue;
        }
      
        if(!fork())
        {
            if(-1 == send(new_fd, "Hello,workd!\n", 14, 0))
            {
                perror("send");
            }
            printf("send Hello, workd!");
            close(new_fd);
            exit(0);
        }

        close(new_fd);
        while(waitpid(-1,NULL,WNOHANG) >0);
    }

    return 0;
}

阅读(3169) | 评论(0) | 转发(0) |
0

上一篇:writen and readn

下一篇:lock

给主人留下些什么吧!~~