Linux 基于父子进程的TCP服务器应用编程

来源:互联网 发布:上海sai软件培训 编辑:程序博客网 时间:2024/05/20 18:53
#include <stdio.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <arpa/inet.h>#define PORTNUM 3333int main(){    int sockfd,sock_fd,ret,readbytes;    char buf[512];    struct sockaddr_in my_addr,your_addr;    int addrlen = sizeof(struct sockaddr);    //socket    sockfd = socket(AF_INET,SOCK_STREAM,0);    if(sockfd == -1)    {        printf("socket error\n");    }    //bind    bzero(&my_addr,sizeof(struct sockaddr_in));    my_addr.sin_family = AF_INET;    my_addr.sin_port = htons(PORTNUM);    my_addr.sin_addr.s_addr = inet_addr("192.168.110.110");    ret = bind(sockfd,(struct sockaddr*)&my_addr,addrlen);        if(ret < 0)    {        printf("bind error\n");    }    //listen    listen(sockfd,10);    while(1)    {        //acceptsock_fd = accept(sockfd,NULL,NULL);if(sock_fd < 0){    printf("accept error\n");}if(fork() == 0){    readbytes = recv(sock_fd,buf,512,0);    buf[readbytes] = '\0';    printf("buf is %s\n",buf);    close(sock_fd);    close(sockfd);    exit(0);}else{    close(sock_fd);}//recv    }}

0 0
原创粉丝点击