1 Star 0 Fork 0

Besti 20155338/Linux 20155338

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
TCPserver.c 2.65 KB
一键复制 编辑 原始数据 按行查看 历史
Besti 20155338 提交于 8年前 . bingfa1
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 155338
#define BACKLOG 1
#define MAXRECVLEN 1024
int main(int argc, char *argv[])
{
char buf[MAXRECVLEN];
int listenfd, connectfd; /* socket descriptors */
struct sockaddr_in server; /* server's address information */
struct sockaddr_in client; /* client's address information */
socklen_t addrlen;
/* Create TCP socket */
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
/* handle exception */
perror("socket() error. Failed to initiate a socket");
exit(1);
}
/* set socket option */
int opt = SO_REUSEADDR;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(listenfd, (struct sockaddr *)&server, sizeof(server)) == -1)
{
/* handle exception */
perror("Bind() error.");
exit(1);
}
if(listen(listenfd, BACKLOG) == -1)
{
perror("listen() error. \n");
exit(1);
}
addrlen = sizeof(client);
while(1){
if((connectfd=accept(listenfd,(struct sockaddr *)&client, &addrlen))==-1)
{
perror("accept() error. \n");
exit(1);
}
FILE *stream;
struct timeval tv;
gettimeofday(&tv, NULL);
printf("You got a connection from client's ip %s, port %d at time %ld.%ld\n",inet_ntoa(client.sin_addr),htons(client.sin_port), tv.tv_sec,tv.tv_usec);
int iret=-1;
char d[1024];
iret = recv(connectfd, buf, MAXRECVLEN, 0);
if(iret>0)
{
strcpy(d,buf);
stream = fopen(buf,"r");
bzero(buf, sizeof(buf));
strcat(buf,"单词数:");
char s[21];
long int count = 0;
while(fscanf(stream,"%s",s)!=EOF)
count++;
char str[10];
sprintf(str, "%ld", count);
int n = sizeof(str);
str[n] = '\0';
strcat(buf,"\n");
strcat(buf,str);
strcat(buf,"(");
strcat(buf,d);
strcat(buf,"单词数)");strcat(buf,"\n");
}else
{
close(connectfd);
break;
}
/* print client's ip and port */
send(connectfd, buf, iret, 0); /* send to the client welcome message */
}
close(listenfd); /* close listenfd */
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Csj996/Besti.git
git@gitee.com:Csj996/Besti.git
Csj996
Besti
Linux 20155338
master

搜索帮助