Just compile the programs
gcc -o client client.c
and
gcc -o server server.c
and run the server in the back ground with
./server &
press enter a couple times then
./client
follow instructions and watch them talk ))
//Client.c
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
int main ()
{
int sockfd;
int len;
struct sockaddr_un address;
int result;
char ch;
int x;
unsigned long u;
//get the character to send
printf("Enter up to 100 characters to send\n");
for(x=0;x<=100;x++)
{
scanf("%c", &ch);
//create a socket for the client
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
//Name the socket as agreed with the server
address.sun_family=AF_UNIX;
strcpy(address.sun_path,"server_socket");
len = sizeof(address);
//Now connect our socket to the server's socket
result = connect(sockfd, (struct sockaddr *)&address, len);
if(result==-1) {
perror("oops: client1");
exit (1);
}
//Now we can read and write via sockfd
printf("\nClient: Ready to write %c to socket\n", ch);
write(sockfd, &ch, 1);
printf("Client: Wrote %c to socket. \n", ch);
read(sockfd, &ch, 1);
printf("Client: Received char from server = %c\n", ch);
//Close the socked
close(sockfd);
}
return (0);
}//end of main
//Server.c
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
int main()
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_un server_address;
struct sockaddr_un client_address;
//Remove any old socket and create an unnamed socket for the server
unlink("server_socket");
server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
//Name the socket
server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, "server_socket");
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
//Create a connection queue and wait for clients.
listen(server_sockfd, 6);
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);
//Read and write to client onclient_sockfd
printf("Server: Getting ready to read\n");
read(client_sockfd, &ch, 1);
printf("Server: Read the character %c\n", ch);
printf("Server: Incremented the character %c to", ch);
ch++;
printf("%c\n", ch);
printf("Server: Ready to write the character %c back\n", ch);
write(client_sockfd, &ch, 1);
printf("Server: Character %c was written.\n", ch);
close(client_sockfd);
}
}