-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverSample.c
More file actions
executable file
·67 lines (52 loc) · 1.41 KB
/
serverSample.c
File metadata and controls
executable file
·67 lines (52 loc) · 1.41 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main( int argc, char **argv )
{
unsigned short port = 0;
int serverSocket = 0;
int clientSocket = 0;
char buffer[1024];
int length = 0;
int value = 1;
struct sockaddr_in address;
struct sockaddr_storage otherAddress;
socklen_t otherSize = sizeof(otherAddress);
//read port from user
printf("Enter port: ");
scanf("%hd", &port);
//get socket
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
//make it able to reuse ports
setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value));
//bind socket to port and local IP
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = INADDR_ANY;
bind(serverSocket, (struct sockaddr*)&address, sizeof(address));
//listen
listen(serverSocket, 1);
//accept
clientSocket = accept( serverSocket, (struct sockaddr *) &otherAddress, &otherSize);
printf("\n\n*Chat Started*\n");
//receive messages
while( (length = recv( clientSocket, buffer, sizeof(buffer) - 1, 0)) > 0 )
{
buffer[length] = '\0';
if( strcmp( buffer, "quit" ) == 0 )
break;
printf("%s\n", buffer);
}
printf("\n*Chat Ended*\n");
//clean up
close( clientSocket );
close( serverSocket );
return 0;
}