Computer Networking
Java Programming
C Programming

How write a client server programs using c?

123

Answer

User Avatar
Wiki User
09/12/2011

I've gotten these working with each other.

CLIENT

Code:

#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> /// CLIENT int main(int argc, char *argv[]) { printf("This is the client program\n"); int sockfd; int len, RC ; struct sockaddr_in address; int result; char ch = 'A'; //Create socket for client. sockfd = socket(PF_INET, SOCK_STREAM, 0); if (sockfd 'A') sleep(5) ; // pause 5 seconds } close(sockfd); exit(0); }

SERVER

Code:

#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> /// SERVER int main(int argc, char *argv[]) { //Declaring process variables. int server_sockfd, client_sockfd; int server_len ; int RC ; unsigned client_len; struct sockaddr_in server_address; struct sockaddr_in client_address; //Remove any old socket and create an unnamed socket for the server. server_sockfd = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htons(INADDR_ANY); server_address.sin_port = htons(7734) ; server_len = sizeof(server_address); RC = bind(server_sockfd, (struct sockaddr *) &server_address, server_len); printf("RC from bind = %d\n", RC ) ; //Create a connection queue and wait for clients RC = listen(server_sockfd, 5); printf("RC from listen = %d\n", RC ) ; client_len = sizeof(client_address); client_sockfd = accept(server_sockfd, (struct sockaddr *) &client_address, &client_len); printf("after accept()... client_sockfd = %d\n", client_sockfd) ; while(1) { char ch; printf("server waiting\n"); //Accept a connection //client_len = sizeof(client_address); //client_sockfd = accept(server_sockfd, (struct sockaddr *) &client_address, &client_len); //printf("after accept()... client_sockfd = %d\n", client_sockfd) ; //Read write to client on client_sockfd RC = read(client_sockfd, &ch, 1); printf("RC from read = %d\n", RC ) ; if (ch=='X') break ; ch++; write(client_sockfd, &ch, 1); } printf("server exiting\n"); //close(client_sockfd); close(client_sockfd); return 0; }