-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_server.c
63 lines (63 loc) · 1.33 KB
/
tcp_server.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
53
54
55
56
57
58
59
60
61
62
63
#include <func.h>
int main(int argc,char *argv[])
{
args_check(argc,3);
int socketfd=socket(AF_INET,SOCK_STREAM,0);
if(-1==socketfd)
{
perror("socket");
return -1;
}
printf("socketfd=%d\n",socketfd);
struct sockaddr_in ser;
memset(&ser,0,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(atoi(argv[2]));
ser.sin_addr.s_addr=inet_addr(argv[1]);
int ret;
ret=bind(socketfd,(struct sockaddr *)&ser,sizeof(ser));
listen(socketfd,10);
int new_fd;
struct sockaddr_in client;
socklen_t addrlen=sizeof(client);
memset(&client,0,sizeof(client));
new_fd=accept(socketfd,(struct sockaddr*)&client,&addrlen);
if(-1==new_fd)
{
perror("accept");
return -1;
}
printf("client ip=%s,port=%d\n",inet_ntoa(client.sin_addr),ntohs(client.sin_port));
char buf[128]={0};
fd_set rdset;
while(1)
{
FD_ZERO(&rdset);
FD_SET(new_fd,&rdset);
FD_SET(STDIN_FILENO,&rdset);
ret=select(new_fd+1,&rdset,NULL,NULL,NULL);
if(ret>0)
{
if(FD_ISSET(STDIN_FILENO,&rdset))
{
memset(buf,0,sizeof(buf));
read(STDIN_FILENO,buf,sizeof(buf)-1);
send(new_fd,buf,strlen(buf),0);
}
if(FD_ISSET(new_fd,&rdset))
{
memset(buf,0,sizeof(buf));
ret=recv(new_fd,buf,sizeof(buf)-1,0);
if(-1==ret)
{
perror("recv");
return -1;
}
printf("%s\n",buf);
}
}
}
close(new_fd);
close(socketfd);
return 0;
}