#include "./stdinc.h" const int MYPORT = 3490; // client connects to this port const int BACKLOG = 10; // max # pending connections main() { int sd; // listen on sd int new_fd; // new connection on new_fd struct sockaddr_in myAddr, // my address clAddr; // client's address char *msg = "Hello World\n"; // reply msg int sinSz = sizeof(struct sockaddr_in); // value-result arg // socklen_t sinSz = sizeof(struct sockaddr_in); // value-result arg if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) FatalPerror("socket error"); myAddr.sin_family = AF_INET; // HBO myAddr.sin_port = htons(MYPORT); // short, NBO myAddr.sin_addr.s_addr = htonl(INADDR_ANY); // any interface; auto-fill with my IP; NBO bzero(&(myAddr.sin_zero), 8); // 0 rest of the struct if (bind(sd, (struct sockaddr *)&myAddr, sizeof(struct sockaddr)) == -1) FatalPerror("bind"); if (listen(sd, BACKLOG) == -1) FatalPerror("listen"); while(1) { // main accept() loop new_fd = accept(sd, (struct sockaddr *) &clAddr, &sinSz); if (new_fd == -1) FatalPerror("accept"); printf("server: got connection from %s\n", inet_ntoa(clAddr.sin_addr)); if (send(new_fd, msg, strlen(msg), 0) == -1) FatalPerror("send"); close(new_fd); } }