-
Notifications
You must be signed in to change notification settings - Fork 1
/
tcpserver.c
68 lines (67 loc) · 1.58 KB
/
tcpserver.c
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
67
68
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define PORT 8080
#define SA struct sockaddr
void chat(int sockfd)
{
char buff[80];
int n;
while(1)
{
strcpy(buff,"\n");
read(sockfd,buff,sizeof(buff));
printf("Client: %s [MSG LENGTH:%d]\n",buff,strlen(buff));
strcpy(buff,"\n");
printf("Server: ");
scanf("%[^\n]%*c", buff);
if(strcmp(buff,"exit")==0)
{
printf("EXIT command detected\n");
exit(0);
}
write(sockfd,buff,sizeof(buff));
}
}
int main()
{
int sockfd,connfd,len;
struct sockaddr_in servaddr, cli;
sockfd=socket(AF_INET, SOCK_STREAM, 0);
if(sockfd==-1)
{
printf("Socket could not be created\n");
exit(0);
}
printf("Socket created successfully\n");
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(PORT);
if((bind(sockfd,(SA*)&servaddr,sizeof(servaddr)))==-1)
{
printf("Failed to bind socket with IP and port\n");
exit(0);
}
printf("Socket bind was successful\n");
if((listen(sockfd,5))!=0)
{
printf("Listen failed\n");
exit(0);
}
printf("Server is listening\n\n\n");
len=sizeof(cli);
connfd=accept(sockfd, (SA*)&cli,&len);
if(connfd==-1)
{
printf("Server accept failed\n");
exit(0);
}
printf("Server is accepting data\n");
chat(connfd);
close(sockfd);
return 0;
}