-
Notifications
You must be signed in to change notification settings - Fork 9
/
echosrv.c
executable file
·52 lines (46 loc) · 1.7 KB
/
echosrv.c
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
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EIXT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(int argc, char const *argv[])
{
int listenfd;
if((listenfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 )
ERR_EIXT("socket failed");
// listenfd = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5188);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); //INADDR_ANY表示本机的任意地址, 网络字节序
// servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //显示指定本机的IP地址
// inet_aton("127.0.0.1", &servaddr.sin_addr)
if(bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
ERR_EIXT("bind failed");
if(listen(listenfd, SOMAXCONN) < 0)
ERR_EIXT("listen failed"); // SOMAXCONN是队列允许的最大值
struct sockaddr_in peeraddr;
socklen_t peerlen = sizeof(peeraddr); //peerlen一定要有初始值
int conn;
if((conn = accept(listenfd, (struct sockaddr*)&peeraddr, &peerlen)) < 0)
ERR_EIXT("accept failed");
char recvbuf[1024];
while(1) {
memset(recvbuf, 0, sizeof(recvbuf));
int ret = read(conn, recvbuf, sizeof(recvbuf)); //conn是已连接套接字, 是主动套接字
fputs(recvbuf, stdout);
write(conn, recvbuf, ret);
}
return 0;
}