2 * a stream socket server demo
8 #include <netinet/in.h>
13 #include <sys/socket.h>
14 #include <sys/types.h>
19 #define MYPORT 1234 // the port users will be connecting to
20 #define BACKLOG 10 // how many pending connections queue will hold
21 #define MAXDATASIZE 1065537
25 sigchld_handler(int s
)
27 while (waitpid(-1, NULL
, WNOHANG
) > 0) {
33 main(int argc
, char *argv
[])
35 int sockfd
, new_fd
; // listen on sock_fd, new connection on new_fd
36 struct sockaddr_in my_addr
; // my address information
37 struct sockaddr_in their_addr
; // connector's address information
41 short int port
= MYPORT
;
42 char buf
[MAXDATASIZE
];
44 if (argc
>= 2 && atoi(argv
[1]) != 0)
47 if ((sockfd
= socket(AF_INET
, SOCK_STREAM
, 0)) == -1) {
52 if (setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(int)) == -1) {
57 memset(&my_addr
, 0, sizeof(my_addr
));
58 my_addr
.sin_family
= AF_INET
;
59 my_addr
.sin_port
= htons(port
);
60 my_addr
.sin_addr
.s_addr
= INADDR_ANY
; // automatically fill with my IP
62 if (bind(sockfd
, (struct sockaddr
*)&my_addr
, sizeof(struct sockaddr
)) == -1) {
67 if (listen(sockfd
, BACKLOG
) == -1) {
72 sa
.sa_handler
= sigchld_handler
; // reap all dead processes
73 sigemptyset(&sa
.sa_mask
);
74 #ifdef HAIKU_TARGET_PLATFORM_HAIKU
75 sa
.sa_flags
= SA_RESTART
;
79 if (sigaction(SIGCHLD
, &sa
, NULL
) == -1) {
86 sin_size
= sizeof(struct sockaddr_in
);
87 if ((new_fd
= accept(sockfd
, (struct sockaddr
*)&their_addr
, &sin_size
)) == -1) {
91 printf("server: got connection from %s\n", inet_ntoa(their_addr
.sin_addr
));
92 if (!fork()) { // this is the child process
93 close(sockfd
); // child doesn't need the listener
97 // child's child process
98 if (fgets(buf
, MAXDATASIZE
, stdin
) == NULL
) {
103 if (!strcmp(buf
, "full\n")) {
106 for (i
= 0; i
< MAXDATASIZE
- 2; i
++) {
107 buf
[i
] = 'a' + (i
% 26);
109 buf
[MAXDATASIZE
- 2] = '\n';
110 buf
[MAXDATASIZE
- 1] = '\0';
113 if (send(new_fd
, buf
, strlen(buf
), 0) == -1) {
122 if ((numBytes
= recv(new_fd
, buf
, MAXDATASIZE
, 0)) == -1) {
129 buf
[numBytes
] = '\0';
131 printf("%s:| %s", inet_ntoa(their_addr
.sin_addr
), buf
);
138 close(new_fd
); // parent doesn't need this