1 #include<stdio.h>
2 #include<sys/types.h>
3 #include<sys/socket.h>
4 #include<stdlib.h>
5 #include<netinet/in.h>
6 #include<errno.h>
7
8
9
10 int init(const char* ip,int port)
11 {
12 int sock = socket(AF_INET,SOCK_STREAM,0);
13 if(sock< 0)
14 {
15 perror("socket\n");
16 exit(2);
17 }
18
19 struct sockaddr_in local;
20 local.sin_family = AF_INET;
21 local.sin_port = htons(port);
22 local.sin_addr.s_addr = inet_addr(ip);
23
24 if(bind(sock, (struct sockaddr*)&local, sizeof(local) )<0)
25 {
26 perror("bind ");
27 exit(3);
28 }
29 if(listen(sock , 5)<0)
30 {
31 perror("listen");
32 }
33 return sock;
34 }
35
36
37 int main(int argc,char* argv[])
38 {
39 if(argc != 3)
40 {
41 printf("use: [ip] [port]\n");
42 exit(1);
43 }
44 int sock = init(argv[1],atoi(argv[2]));
45 struct sockaddr_in remote;
46 int len =sizeof(remote);
47 while(1)
48 {
49 int new_fd = accept(sock ,(struct sockaddr*)&remote ,
&len );
50 char buf[1024];
51 printf("get a new connect:%s %d\n",inet_ntoa
(remote.sin_addr.s_addr),ntohs(remote.sin_port));
52 if(new_fd >0)
53 {
54
55 while(1)
56 {
57 if(new_fd >0)
58 {
59 ssize_t s = read(new_fd,buf,sizeof(buf));
60 if( s > 0)
61 {
62 buf[s] = 0;
63 printf("client: %s\n",buf);
64 }
65 else if(s ==0 )
66 {
67 printf("connect closed \n");
68 break;
69 }
70 else
71 {
72
73 perror("read...\n");
74 break;
75 }
76 }
77 }
78 }
79 }
80 return 0;
81 }
写着玩的。
最大最大的缺点:同一时间只能有一个连接。