socket_1

linux socket server

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

#include<sys/socket.h>
#include<unistd.h>
#include <netdb.h>
#include<stdlib.h>
#include<netinet/in.h>
#include <sys/types.h>
#include <netinet/in.h>
#include<stdio.h>
#include <arpa/inet.h>
int main(int argc, char const *argv[])
{

int sockfd,client_sockfd;

struct sockaddr_in my_addr,client_addr;

int addr_len;

my_addr.sin_family = AF_INET;

my_addr.sin_port = htons(9000);

my_addr.sin_addr.s_addr=INADDR_ANY;

sockfd = socket(AF_INET,SOCK_STREAM,0);

bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr));


//max queue 10
listen(sockfd,10);

addr_len = sizeof(struct sockaddr);

while (1)
{

printf("server is waiting for client to connect:\n");


socklen_t client_size;

client_sockfd = accept(sockfd, (struct sockaddr *)&client_addr,&client_size);

printf("Client ip address=%s\n",inet_ntoa(client_addr.sin_addr));

char *hello = "hello";

send(client_sockfd,hello,sizeof(hello),0);

printf("disconnect the client request\n");

close(client_sockfd);

}

close(sockfd);

return 0;
}

打完收工