

















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
The code and explanation for creating a simple tcp client-server application using winsock in c. The client connects to the server, receives a string, and exits, while the server waits for new connections and sends back a greeting.
Typology: Slides
1 / 25
This page cannot be seen from the preview
Don't miss anything!


















if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { fprintf(stderr, "WSAStartup failed.\n"); exit(1); }
int WSAStartup( WORD wVersionRequested, LPWSADATA lpWSAData ); The WSAStartup function must be the first Windows Sockets function called by an application or DLL. It allows an applicati on or DLL to specify the version of Windows Sockets required and retrieve details of the specific Windows Sockets implemen tation. The application or DLL can only issue further Windows Sockets functions after successfully calling WSAStartup.
if (argc != 2) { fprintf(stderr,"usage: client serverIP\n"); exit(1); }
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); WSACleanup( ); exit(1); }
their_addr.sin_family = AF_INET; // host byte order their_addr.sin_port = htons(PORT); // network byte order their_addr.sin_addr.s_addr = inet_addr(argv[1]); memset(&(their_addr.sin_zero), 0, 8); // zero rest of the struct
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr_in)) == -1) { perror("connect"); WSACleanup( ); exit(1); }
buf[numbytes] = 0; printf("Received: %s",buf); closesocket(sockfd); WSACleanup( ); return 0; } //main ends here
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