//==================================================================================== // The information contained herein is the exclusive property of // XXXXXX Co. And shall not be distributed, reproduced, // or disclosed in whole in part without prior written permission. // (C) COPYRIGHT 2003 XXXXXX CO. // ALL RIGHTS RESERVED // The entire notice above must be reproduced on all authorized copies. //==================================================================================== //============================================================= // 文件名称:tcp_echo_srv.c // 功能描述:TCP Echo Server // 维护记录:2008-12-25 V1.0 //============================================================= #include <stdio.h> #include <stdlib.h> #include <string.h> // bzero
#include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> // inet_ntop //============================================================= // 语法格式: void main(void) // 实现功能: 主函数,建立一个TCP Echo Server // 入口参数: 无 // 出口参数: 无 //============================================================= int main(int argc, char *argv[]) { char recvbuf[2048]; // 接收缓冲区 int sockfd; // 套接字 struct sockaddr_in servAddr; // 服务器地址结构体 unsigned short port = 8000; // 监听端口 if(argc > 1) // 由参数接收端口 { port = atoi(argv[1]); } printf("TCP Server Started at port %d!\n", port); sockfd = socket(AF_INET, SOCK_STREAM, 0); // 创建TCP套接字 if(sockfd < 0) { perror("Invalid socket"); exit(1); } bzero(&servAddr, sizeof(servAddr)); // 初始化服务器地址 servAddr.sin_family = AF_INET; servAddr.sin_port = htons(port); servAddr.sin_addr.s_addr = htonl(INADDR_ANY); printf("Binding server to port %d\n", port); if(bind(sockfd, (struct sockaddr*)&servAddr, sizeof(struct sockaddr)) != 0) { close(sockfd); perror("binding err!"); exit(1); } if(listen(sockfd, 1) != 0) { close(sockfd); perror("listen err!"); exit(1); } printf("waiting client...\n"); while(1) { char cliIP[INET_ADDRSTRLEN]; // 用于保存客户端IP地址 size_t recvLen; struct sockaddr_in cliAddr; // 用于保存客户端地址 size_t cliAddrLen = sizeof(cliAddr); // 必须初始化!!!
int connfd = accept(sockfd, (struct sockaddr*)&cliAddr, &cliAddrLen); // 获得一个已经建立的连接 if(connfd < 0) { close(sockfd); perror("accept err!"); exit(1); } inet_ntop(AF_INET, &cliAddr.sin_addr.s_addr, cliIP, INET_ADDRSTRLEN); printf("client ip = %s\n", cliIP); while((recvLen = read(connfd, recvbuf, 2048)) > 0) { write(connfd, recvbuf, recvLen); } close(connfd); printf("client closed!\n"); } close(sockfd); return 0; }
|