1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
/*============================================================================ Name : server.c Author : Vach Description : Hello World in C, Ansi-style ============================================================================*/ #include <stdlib.h> #include <pthread.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> /* inet(3) functions */ #include <stdlib.h> #include <errno.h> #include <stdio.h> #include <string.h>
int handle(int point);
int main(void) { int sfd, ind; struct sockaddr_in addr; struct sockaddr_in clent; char resv[1024], sendbuf[1024]; char buf[1024]; char * myaddr = "192.168.231.128"; int ret; // 返回值设置 socklen_t lent; int pid; addr.sin_family = AF_INET; //IPv4 Internet protocols addr.sin_port = htons(5050); //这里输入服务器端口号 addr.sin_addr.s_addr = inet_addr(myaddr);; //INADDR_ANY表示本机IP//獲取socket描述符,IPV4asd printf("socket start n"); sfd = socket(AF_INET, SOCK_STREAM, 0); if (sfd < 0) { printf("socket error n"); return -1; } printf("bind start n");//将套接子与指定端口链接 if (bind(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr)) < 0) { printf("bind error n"); return -1; }//监听套接子 printf("listen start n"); if (listen(sfd, 1024) < 0) { printf("listen error n"); return -1;} for (;;) { //接受来自客户端的信息 printf("accept start n"); memset(&clent, 0, sizeof(clent)); lent = sizeof(clent); ind = accept(sfd, (struct sockaddr *) &clent, &lent); if (ind < 0) { printf("accept error %d n", ind); return -1; } printf("infor n"); printf("clent addr%s porit %dn",inet_ntop(AF_INET, &clent.sin_addr, buf, sizeof(buf)),ntohs(clent.sin_port)); pid = fork(); if (pid == 0) {//子进程 close(sfd); handle(ind); } else if (pid < 0) { //error close(ind); } else {//父进程 } } return EXIT_SUCCESS; } int handle(int point) { int retn;char buf[1024]; for (;;) { retn = read(point, buf, sizeof(buf)); if (retn < 0) { printf("read error n"); close(point); break; } else if (retn == 0) { printf("client exit n"); close(point); break; } printf("client:%sn", buf); if (strcmp("exit", buf) == 0) { printf("exit n"); close(point); return 0; } return 0; }
|
近期评论