Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
apsrcreatix
GitHub Repository: apsrcreatix/Socket-Programming-With-C
Path: blob/master/06-half-duplex-chat-tcp-ip/client.c
137 views
1
/*
2
* Title : Half duplex client side
3
* Name : Aditya Pratap Singh Rajput
4
* Subject : Network Protocols And Programming using C
5
*
6
Note : please consider the TYPOS in comments.
7
Thanks.
8
*/
9
10
#include "stdio.h"
11
#include "stdlib.h"
12
#include "string.h"
13
//headers for socket and related functions
14
#include <sys/types.h>
15
#include <sys/socket.h>
16
//for including structures which will store information needed
17
#include <netinet/in.h>
18
#include <unistd.h>
19
//for gethostbyname
20
#include "netdb.h"
21
#include "arpa/inet.h"
22
23
//defines
24
#define h_addr h_addr_list[0] /* for backward compatibility */
25
26
#define PORT 9002 // port number
27
#define MAX 1000 //maximum buffer size
28
29
//main function
30
int main(){
31
char serverResponse[MAX];
32
char clientResponse[MAX];
33
34
//creating a socket
35
int socketDescriptor = socket(AF_INET, SOCK_STREAM, 0);
36
37
//placeholder for the hostname and my ip address
38
char hostname[MAX], ipaddress[MAX];
39
struct hostent *hostIP; //placeholder for the ip address
40
//if the gethostname returns a name then the program will get the ip address
41
if(gethostname(hostname,sizeof(hostname))==0){
42
hostIP = gethostbyname(hostname);//the netdb.h fucntion gethostbyname
43
}else{
44
printf("ERROR:FCC4539 IP Address Not ");
45
}
46
47
struct sockaddr_in serverAddress;
48
serverAddress.sin_family = AF_INET;
49
serverAddress.sin_port = htons(PORT);
50
serverAddress.sin_addr.s_addr = INADDR_ANY;
51
52
connect(socketDescriptor, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
53
54
// getting the address port and remote host
55
printf("\nLocalhost: %s\n", inet_ntoa(*(struct in_addr*)hostIP->h_addr));
56
printf("Local Port: %d\n", PORT);
57
printf("Remote Host: %s\n", inet_ntoa(serverAddress.sin_addr));
58
59
while (1)
60
{ //recieve the data from the server
61
recv(socketDescriptor, serverResponse, sizeof(serverResponse), 0);
62
//recieved data from the server successfully then printing the data obtained from the server
63
printf("\nSERVER : %s", serverResponse);
64
65
printf("\ntext message here... :");
66
scanf("%s", clientResponse);
67
send(socketDescriptor, clientResponse, sizeof(clientResponse), 0);
68
}
69
70
//closing the socket
71
close(socketDescriptor);
72
return 0;
73
}
74