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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(void) {
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if(lfd <=0 ) {
perror("socket error");
exit(1);
}
struct sockaddr_in serv;
bzero(&serv, sizeof (serv));
serv.sin_family = AF_INET;
serv.sin_port = htons(8888);
serv.sin_addr.s_addr = htonl(INADDR_ANY); //使用本机任意可用IP
//绑定IP 端口
int ret = bind(lfd,(struct sockaddr *)&serv,sizeof serv);
if(ret <0) {
perror(" error ");
return -1;
}
listen(lfd,128);
//最大监听 128
int cfd = accept(lfd, NULL, NULL);
printf("lfd = [%d] , cfd = [%d]", lfd,cfd);
int n = 0;
char buf[1024];
while(1) {
memset(buf,0x00,sizeof buf);
n = read(cfd,buf, sizeof(buf));
if(n<=0) {
// 关闭连接,跳出循环
printf("close, n := %d",n);
break;
}
printf("n=%d , buf =%s\n", n, buf);
// for(int i=0;i<n;++i) {
// buf[i] = toupper(buf[i]);
// }
//发送数据
write(cfd,buf,n);
}
close(lfd);
close(cfd);
return 0;
}
/*
测试脚本
nc 127.0.0.1 8888
hello
world
*/
|