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

C TCP Client-Server Example Code

The document contains a simple client-server program implemented in C using TCP sockets. The server listens on port 8080, accepts a connection, reads a message from the client, and sends a reply. The client connects to the server, sends a message, and prints the server's response.

Uploaded by

smanjuravi
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)
26 views2 pages

C TCP Client-Server Example Code

The document contains a simple client-server program implemented in C using TCP sockets. The server listens on port 8080, accepts a connection, reads a message from the client, and sends a reply. The client connects to the server, sends a message, and prints the server's response.

Uploaded by

smanjuravi
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-Server Program in C (TCP Sockets)

Server Code (server.c):


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>

#define PORT 8080

int main() {
int server_fd, new_socket;
struct sockaddr_in address;
char buffer[1024] = {0};
int addrlen = sizeof(address);

server_fd = socket(AF_INET, SOCK_STREAM, 0);


address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);

bind(server_fd, (struct sockaddr *)&address, sizeof(address));


listen(server_fd, 3);
new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);

read(new_socket, buffer, 1024);


printf("Client: %s\n", buffer);
char *reply = "Hello from server!";
send(new_socket, reply, strlen(reply), 0);

close(new_socket);
close(server_fd);
return 0;
}

Client Code (client.c):


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 8080

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

sock = socket(AF_INET, SOCK_STREAM, 0);


serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
inet_pton(AF_INET, "[Link]", &serv_addr.sin_addr);

connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));


char *msg = "Hello from client!";
send(sock, msg, strlen(msg), 0);
read(sock, buffer, 1024);
printf("Server: %s\n", buffer);
close(sock);

return 0;
}

You might also like