0% found this document useful (0 votes)
5 views

tcp server prgm

Uploaded by

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

tcp server prgm

Uploaded by

ashna bs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>

#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(void)
{
int socket_desc, client_sock, client_size;
struct sockaddr_in server_addr, client_addr;
char server_message[2000], client_message[2000];

// Create socket:
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
printf("Socket created successfully\n");

// Set port and IP:


server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(2000);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

// Bind to the set port and IP:


bind(socket_desc, (struct sockaddr*)&server_addr, sizeof(server_addr));
printf("Done with binding\n");

// Listen for clients:


listen(socket_desc, 1);
printf("\nListening for incoming connections.....\n");

// Accept an incoming connection:


client_size = sizeof(client_addr);
client_sock = accept(socket_desc, (struct sockaddr*)&client_addr, &client_size);
printf("Client connected at IP: %s and port: %i\n", inet_ntoa(client_addr.sin_addr),
ntohs(client_addr.sin_port));

// Receive client's message:


recv(client_sock, client_message, sizeof(client_message),0);
printf("Msg from client: %s\n", client_message);

// Respond to client:
strcpy(server_message, "This is the server's message.");

send(client_sock, server_message, strlen(server_message), 0);

// Closing the socket:


close(client_sock);
close(socket_desc);
return 0;
}

You might also like