#include #include #include #include #include #include #include #include #define MYPORT 3490 /* the port users will be connecting to */ #define BACKLOG 10 /* how many pending connections queue will hold */ int main(int argc, char *argv[]) { int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd */ struct sockaddr_in my_addr; /* my address information */ struct sockaddr_in their_addr; /* connector's address information */ socklen_t sin_size; sockfd = socket(AF_INET, SOCK_STREAM, 0); /* do some error checking! */ my_addr.sin_family = AF_INET; /* host byte order */ my_addr.sin_port = htons(MYPORT); /* short, network byte order */ my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */ memset(&(my_addr.sin_zero), 8, 0); /* zero the rest of the struct */ /* don't forget your error checking for these calls: */ bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)); listen(sockfd, BACKLOG); sin_size = sizeof(struct sockaddr_in); int child_n; for (int i=1; true; i++) { printf("I am the dad!\n"); printf("Ok, I will sleep waiting for a sucker to connect on %d\n", MYPORT); new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); child_n = i; pid_t pid = fork(); if (pid == 0) break; } char buf[200]; printf("%d: Ok, I am the kid, going into a loop servicing the socket\n", child_n); write(new_fd, "Hello!\n", 8); while (true) { //char * mys = "Hurry, send something, I'm waiting!\n"; //printf("%d: Sending this insult: %s\n", child_n, mys); //write(new_fd, mys, strlen(mys) + 1); int n = read(new_fd, buf, sizeof(buf) - 1); if (n < 0) { perror("reading socket"); break; } else if (n > 0) { buf[n] = '\0'; printf("%d: Msg: %s\n", child_n, buf); char reply[200]; snprintf(reply, sizeof(reply), "Cool, got your message:\n %s\nTHANKS!!\n", buf); write(new_fd, reply, strlen(reply) + 1); if (0 == strncasecmp(buf, "quit", 4)) { break; } } else { printf("%d: 0 bytes read, probably an error!\n", child_n); break; } usleep(100000); printf("%d: Next Loop . . . \n", child_n); } printf("Help me, I am the kid, I will die . . . . \n"); }