|
发表于 2003-7-30 18:49:55
|
显示全部楼层
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <netinet/in.h>
- #include <sys/socket.h>
- int
- main(void)
- {
- int sockfd, fd;
- struct sockaddr_in saddr, caddr;
- int n, addr_size;
- char buf[1024];
- FILE *fp;
- extern int errno;
- if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
- perror("socket error");
- exit(-1);
- }
- bzero(&saddr, sizeof(saddr));
- saddr.sin_family = AF_INET;
- saddr.sin_port = htons(12345);
- saddr.sin_addr.s_addr = htonl(INADDR_ANY);
- if(bind(sockfd, (struct sockaddr *)&saddr, sizeof(struct sockaddr)) == -1){
- perror("bind error");
- exit(-1);
- }
- if(listen(sockfd, 1) == -1){
- perror("listen error");
- exit(-1);
- }
- for(;;){
- addr_size = sizeof(struct sockaddr_in);
- if((fd = accept(sockfd, (struct sockaddr *)&caddr, &addr_size)) == -1){
- perror("accept error");
- continue;
- }
- for(;;){
- if((n = read(fd, buf, 1023)) < 0){
- perror("read error");
- continue;
- }
- buf[n - 2] = '\0'; /* 去除/r/n */
- if(!strcasecmp(buf, "exit"))
- break;
- if((fp = popen(buf, "r")) == NULL){
- snprintf(buf, 1023, "ERROR: %s", strerror(errno));
- write(fd, buf, strlen(buf));
- continue;
- }
- while(fgets(buf, 1023, fp))
- write(fd, buf, strlen(buf));
- pclose(fp);
- }
- close(fd);
- }
- exit(0);
- }
复制代码
用telnet localhost 12345连接。
只能返回stdout的输出,对stderr的输出是在服务器端输出的,输入的命令不能是交互式的。 |
|