Path: blob/master/06-half-duplex-chat-tcp-ip/client.c
137 views
/*1* Title : Half duplex client side2* Name : Aditya Pratap Singh Rajput3* Subject : Network Protocols And Programming using C4*5Note : please consider the TYPOS in comments.6Thanks.7*/89#include "stdio.h"10#include "stdlib.h"11#include "string.h"12//headers for socket and related functions13#include <sys/types.h>14#include <sys/socket.h>15//for including structures which will store information needed16#include <netinet/in.h>17#include <unistd.h>18//for gethostbyname19#include "netdb.h"20#include "arpa/inet.h"2122//defines23#define h_addr h_addr_list[0] /* for backward compatibility */2425#define PORT 9002 // port number26#define MAX 1000 //maximum buffer size2728//main function29int main(){30char serverResponse[MAX];31char clientResponse[MAX];3233//creating a socket34int socketDescriptor = socket(AF_INET, SOCK_STREAM, 0);3536//placeholder for the hostname and my ip address37char hostname[MAX], ipaddress[MAX];38struct hostent *hostIP; //placeholder for the ip address39//if the gethostname returns a name then the program will get the ip address40if(gethostname(hostname,sizeof(hostname))==0){41hostIP = gethostbyname(hostname);//the netdb.h fucntion gethostbyname42}else{43printf("ERROR:FCC4539 IP Address Not ");44}4546struct sockaddr_in serverAddress;47serverAddress.sin_family = AF_INET;48serverAddress.sin_port = htons(PORT);49serverAddress.sin_addr.s_addr = INADDR_ANY;5051connect(socketDescriptor, (struct sockaddr *)&serverAddress, sizeof(serverAddress));5253// getting the address port and remote host54printf("\nLocalhost: %s\n", inet_ntoa(*(struct in_addr*)hostIP->h_addr));55printf("Local Port: %d\n", PORT);56printf("Remote Host: %s\n", inet_ntoa(serverAddress.sin_addr));5758while (1)59{ //recieve the data from the server60recv(socketDescriptor, serverResponse, sizeof(serverResponse), 0);61//recieved data from the server successfully then printing the data obtained from the server62printf("\nSERVER : %s", serverResponse);6364printf("\ntext message here... :");65scanf("%s", clientResponse);66send(socketDescriptor, clientResponse, sizeof(clientResponse), 0);67}6869//closing the socket70close(socketDescriptor);71return 0;72}7374