

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A c code example of a simple socket server using winsock library. The server listens for incoming connections, accepts new connections, and sends a 'hello, world!' message to the client.
Typology: Exercises
1 / 2
This page cannot be seen from the preview
Don't miss anything!


#include #include #include #include
#define MYPORT 13490 // the port users will be connecting to #define BACKLOG 10 // how many pending connections queue will hold int main (int arc, char *argv[]) { int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct sockaddr_in my_addr; // Local address information struct sockaddr_in their_addr; // client’s address information int sin_size; int numBytes; char *d; WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { fprintf(stderr, "WSAStartup failed.\n"); exit(1); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); WSACleanup( ); exit(1); } my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(MYPORT); // network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(&(my_addr.sin_zero), 0, 8); // zero rest of the struct if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); WSACleanup( ); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); WSACleanup( );
exit(1); } sin_size = sizeof(struct sockaddr_in); fprintf(stderr, "Waiting for client to connect"); while(1) { if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n", d = inet_ntoa(their_addr.sin_addr)); printf("%s",d); if ((numBytes=send(new_fd, "Hello, world!\n", 14, 0)) == -1) { perror("send"); } fprintf(stderr, "%d bytes sent to client\n",numBytes); closesocket(new_fd); WSACleanup( ); return 0; } } //main ends here