Sunday, January 5, 2014

Socket Programming In C (TCP)


tcpserver.c
 
#include"stdio.h"
#include"stdlib.h"
#include"sys/types.h"
#include"sys/socket.h"
#include"string.h"
#include"netinet/in.h"

#define PORT 4444
#define BUF_SIZE 20

void main() {
 struct sockaddr_in addr, cl_addr;
 int sockfd, len, ret, newsockfd;
 char buffer[BUF_SIZE];
 
 sockfd = socket(AF_INET, SOCK_STREAM, 0);
 if (sockfd < 0) {
  printf("Error creating socket!\n");
  exit(1);
 }
 printf("Socket created...\n");
 
 memset(&addr, 0, sizeof(addr));
 addr.sin_family = AF_INET;
 addr.sin_addr.s_addr = INADDR_ANY;
 addr.sin_port = PORT;
 
 ret = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
 if (ret < 0) {
  printf("Error binding!\n");
  exit(1);
 }
 printf("Binding done...\n");

 printf("Waiting for a connection...\n");
 listen(sockfd, 5);

 len = sizeof(cl_addr);
 newsockfd = accept(sockfd, (struct sockaddr *) &cl_addr, &len);
 if (newsockfd < 0) {
  printf("Error accepting connection!\n");
  exit(1);
 }
 printf("Connection accepted...\n"); 

 memset(buffer, 0, BUF_SIZE);
 ret = recv(newsockfd, buffer, BUF_SIZE, 0);
 if(ret < 0) {
  printf("Error receiving data!\n");  
  exit(1);
 }
 printf("Received data: %s\n", buffer); 
}


tcpclient.c
 
#include"stdio.h"
#include"stdlib.h"
#include"sys/types.h"
#include"sys/socket.h"
#include"string.h"
#include"netinet/in.h"

#define PORT 4444

void main() {
 struct sockaddr_in addr, cl_addr;
 int sockfd, ret;
 char * buffer="hi there?";
 
 sockfd = socket(AF_INET, SOCK_STREAM, 0);
 if (sockfd < 0) {
  printf("Error creating socket!\n");
  exit(1);
 }
 printf("Socket created...\n");
 
 memset(&addr, 0, sizeof(addr));
 addr.sin_family = AF_INET;
 addr.sin_addr.s_addr = INADDR_ANY;
 addr.sin_port = PORT;   

 ret = connect(sockfd, (struct sockaddr *) &addr, sizeof(addr));
 if (ret < 0) {
  printf("Error connecting to the server!\n");
  exit(1);
 }
 printf("Connected to the server...\n");
 
 ret = send(sockfd, buffer, strlen(buffer), 0);
 if (ret < 0) {
  printf("Error sending data!\n");
  exit(1);
 }
 printf("Sent data: %s\n", buffer);
}

Executing the program
(in first terminal)
gcc tcpserver.c -o server
./server

(in second terminal)
gcc tcpclient.c -o client
./client

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *