// Client side program
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int sockfd, len, result;
struct sockaddr_in address;
char name[100], ser[100];
// Create socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("Socket creation failed");
exit(1);
}
// Set up the server address struct
address.sin_family = AF_INET;
address.sin_port = htons(9001);
address.sin_addr.s_addr = inet_addr("127.0.0.1");
len = sizeof(address);
// Connect to the server
result = connect(sockfd, (struct sockaddr *) &address, len);
if (result == -1)
{
perror("Unable to connect");
close(sockfd);
exit(1);
}
// Send message to server
printf("Enter the message: ");
fgets(name, sizeof(name), stdin);
write(sockfd, name, strlen(name) + 1);
// Read message from server
memset(ser, 0, sizeof(ser));
read(sockfd, ser, sizeof(ser));
printf("\nReading from server: \n");
puts(ser);
// Close the socket
close(sockfd);
return 0;
}
0 Comments