Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
client.c File Reference

Client side implementation of Server-Client system. More...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
Include dependency graph for client.c:

Macros

#define MAX   80
 max.
 
#define PORT   8080
 port number to connect to
 
#define SA   struct sockaddr
 shortname for sockaddr
 

Functions

void func (int sockfd)
 Continuous loop to send and receive over the socket.
 
int main ()
 Driver code.
 

Detailed Description

Client side implementation of Server-Client system.

Author
Nairit11
Krishna Vedala
See also
client_server/server.c

Macro Definition Documentation

◆ MAX

#define MAX   80

max.

characters per message

Function Documentation

◆ func()

void func ( int  sockfd)

Continuous loop to send and receive over the socket.

Exits when "exit" is sent from commandline.

Parameters
sockfdsocket handle number
38{
39 char buff[MAX];
40 int n;
41 for (;;)
42 {
43 bzero(buff, sizeof(buff));
44 printf("Enter the string : ");
45 n = 0;
46 while ((buff[n++] = getchar()) != '\n')
47 {
48 ;
49 }
50 write(sockfd, buff, sizeof(buff));
51 bzero(buff, sizeof(buff));
52 read(sockfd, buff, sizeof(buff));
53 printf("From Server : %s", buff);
54 if ((strncmp(buff, "exit", 4)) == 0)
55 {
56 printf("Client Exit...\n");
57 break;
58 }
59 }
60}
#define MAX
max.
Definition client.c:28

◆ main()

int main ( void  )

Driver code.

71{
72#ifdef _WIN32
73 // when using winsock2.h, startup required
74 WSADATA wsData;
75 if (WSAStartup(MAKEWORD(2, 2), &wsData) != 0)
76 {
77 perror("WSA Startup error: \n");
78 return 0;
79 }
80
81 atexit(cleanup); // register at-exit function
82#endif
83
84 int sockfd, connfd;
85 struct sockaddr_in servaddr, cli;
86
87 // socket create and verification
88 sockfd = socket(AF_INET, SOCK_STREAM, 0);
89 if (sockfd == -1)
90 {
91 printf("socket creation failed...\n");
92 exit(0);
93 }
94 else
95 {
96 printf("Socket successfully created..\n");
97 }
98 bzero(&servaddr, sizeof(servaddr));
99
100 // assign IP, PORT
101 servaddr.sin_family = AF_INET;
102 servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
103 servaddr.sin_port = htons(PORT);
104
105 // connect the client socket to server socket
106 if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) != 0)
107 {
108 printf("connection with the server failed...\n");
109 exit(0);
110 }
111 else
112 {
113 printf("connected to the server..\n");
114 }
115
116 // function for chat
117 func(sockfd);
118
119 // close the socket
120 close(sockfd);
121 return 0;
122}
#define SA
shortname for sockaddr
Definition client.c:30
#define PORT
port number to connect to
Definition client.c:29
void func(int sockfd)
Continuous loop to send and receive over the socket.
Definition client.c:37
Here is the call graph for this function: