-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_socket_communication.c
More file actions
49 lines (41 loc) · 1.25 KB
/
client_socket_communication.c
File metadata and controls
49 lines (41 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <arpa/inet.h>
#include <stdio.h>
#include <sys/types.h> //socket
#include <sys/socket.h> //socket
#include <string.h> //memset
#include <stdlib.h> //sizeof
#include <netinet/in.h> //INADDR_ANY
#define PORT 8000
#define SERVER_IP "127.0.0.1"
#define MAXSZ 100
int main()
{
int sockfd; // to create socket
struct sockaddr_in serverAddress; // client will connect on this
int n;
char msg1[MAXSZ];
char msg2[MAXSZ];
// create socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// initialize the socket addresses
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(SERVER_IP);
serverAddress.sin_port = htons(PORT);
//
// //client connect to server on port
connect(sockfd, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
// send to sever and receive from server
while (1)
{
printf("\nEnter message to send to server:\n");
fgets(msg1, MAXSZ, stdin);
if (msg1[0] == '#')
break;
n = strlen(msg1) + 1;
send(sockfd, msg1, n, 0);
n = recv(sockfd, msg2, MAXSZ, 0);
printf("Receive message from server::%s\n", msg1);
}
return 0;
}