0% found this document useful (0 votes)
4 views2 pages

C Client Socket Program Example

The document provides a C program for a client socket that connects to a server on localhost at port 8080. It prompts the user to input a bit stream of 0s and 1s, sends it to the server, and then reads and displays the response. The program includes error handling for socket creation, address conversion, and connection failures.

Uploaded by

super simran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

C Client Socket Program Example

The document provides a C program for a client socket that connects to a server on localhost at port 8080. It prompts the user to input a bit stream of 0s and 1s, sends it to the server, and then reads and displays the response. The program includes error handling for socket creation, address conversion, and connection failures.

Uploaded by

super simran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Client Socket Program in C

// client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080


#define BUFFER_SIZE 1024

int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
char input[BUFFER_SIZE];

// Create socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);

// Convert IPv4 and IPv6 addresses from text to binary form


if (inet_pton(AF_INET, "[Link]", &serv_addr.sin_addr) <= 0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}

// Connect to the server


if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}

// Get bit stream input from user


printf("Enter a bit stream (only 0s and 1s): ");
scanf("%s", input);
// Send the bit stream to the server
send(sock, input, strlen(input), 0);
printf("Bit stream sent to server: %s\n", input);

// Read the response from the server


read(sock, buffer, BUFFER_SIZE);
printf("Received stuffed bit stream from server: %s\n", buffer);

// Close the socket


close(sock);
return 0;
}

You might also like