Linux_C socket 服务器与客户端交互程序(输入小写转换为大写)

client.c

 1 /* interactionSocket/client.c
 2  *                 实现终端与服务器端的交互式输入输出
 3  */
 4 #include <stdio.h>
 5 #include <stdlib.h>
 6 #include <string.h> 
 7 #include <unistd.h>
 8 #include <sys/types.h> 
 9 #include <sys/socket.h>
10 #include <netinet/in.h>
11 #include <netdb.h>
12 
13 #define MAXLINE 80
14 #define PORTNUM 12345
15 
16 int main(void) {
17   int sock, len;
18   struct sockaddr_in saddr;
19   struct hostent *hp;
20   char buf[MAXLINE];
21   char request[MAXLINE];
22   char hostname[BUFSIZ];
23 
24   sock=socket(AF_INET, SOCK_STREAM, 0);
25   if(sock==-1) exit(-1);
26   
27   bzero((void*)&saddr, sizeof(saddr));
28   //inet_pton(AF_INET, "127.0.0.1", (void*)&saddr.sin_addr);
29   gethostname(hostname, BUFSIZ);
30   hp=gethostbyname(hostname);
31   bcopy(hp->h_addr, (void*)&saddr.sin_addr, hp->h_length);
32   saddr.sin_port=htons(PORTNUM);
33   saddr.sin_family=AF_INET;
34   
35   connect(sock, (struct sockaddr *)&saddr, sizeof(saddr));
36   while( fgets(buf, MAXLINE, stdin)!=NULL) {
37     write(sock, buf, strlen(buf));
38     len=read(sock, buf, MAXLINE);
39     if(len==0)
40       printf("the other side has been closed");
41     else 
42       write(STDOUT_FILENO, buf, len);
43   }
44   close(sock);
45   return 1;
46 }

server.c

 1 /* interaction/server.c
 2  */
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 #include <netinet/in.h>
 6 #include <sys/types.h>
 7 #include <sys/socket.h>
 8 #include <string.h>
 9 #include <netdb.h>
10 
11 #define MAXLINE 80
12 #define SERV_PORT 12345
13 #define BACKLOG 20
14 int main(void ) {
15   int sock, connfd;
16   struct sockaddr_in saddr, cliaddr;
17   struct hostent *hp;
18   socklen_t cliaddr_len;
19   char buf[MAXLINE];
20   char str[MAXLINE];
21   char hostname[BUFSIZ];
22   int i, n;
23   
24   sock=socket(PF_INET, SOCK_STREAM, 0);
25   if(sock==-1)
26     exit(-1);
27   bzero((void*)&saddr, sizeof(saddr));
28   //saddr.sin_addr.s_addr=htonl(INADDR_ANY);
29   gethostname(hostname, BUFSIZ);
30   hp=gethostbyname(hostname);
31   bcopy(hp->h_addr, (void*)&saddr.sin_addr, hp->h_length);
32   saddr.sin_family=AF_INET;
33   saddr.sin_port=htons(SERV_PORT);
34   if(bind(sock, (struct sockaddr*)&saddr, sizeof(saddr))==-1)
35     exit(-1);
36   if(listen(sock, BACKLOG)==-1)
37     exit(-1);
38   printf("accepting connections...\n");
39   while(1) {
40     cliaddr_len=sizeof(cliaddr);
41     connfd=accept(sock, (struct sockaddr*)&cliaddr, &cliaddr_len);
42     while(1) {
43       n=read(connfd, buf, MAXLINE);
44       if(n==0){ 
45     printf("the other side has been closed.\n");
46     break;
47       }
48       //printf("received from %s at PORT %d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str)), ntohs(cliaddr.sin_port));
49       for(i=0; i<n; i++) 
50     buf[i]=toupper(buf[i]);
51       write(connfd, buf, n);
52     }
53     close(connfd);
54   }
55 }

 

posted on 2014-11-15 20:32  Zachary_wiz  阅读(544)  评论(0编辑  收藏  举报

导航