OneCompiler

TCP SERVER

128

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>

int main()
{

//creating socket
int server_socket;
server_socket = socket(AF_INET,SOCK_STREAM,0);

//defining address structure
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(8080);
server_address.sin_addr.s_addr = INADDR_ANY;

//binding to IP and port
bind(server_socket,(struct addr*)&server_address,sizeof(server_address));

//listening to the connections
listen(server_socket,5);

//accepting the connections
//and put that connection into another socket
int client_socket;
client_socket = accept(server_socket,NULL,NULL);

//receiving the phone number from client
char phone_num[1000];
recv(client_socket,phone_num,sizeof(phone_num),0);
printf("Data received by server : %s\n",phone_num);

//Generating an OTP from server
int OTP[1];
OTP[0] = 4561;

//sending this OTP to client
send(client_socket,OTP,sizeof(OTP),0);
printf("Server sends : %d\n",OTP[0]);

//closing the socket
close(server_socket);

return 0;
}