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
| #include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
void ErrorAndExit(const char *str);
#define IP "127.0.0.1" /* Local Host OR Should be your local IP for test */
#define PORT 5000
int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr = {0};
if( (listenfd = socket(AF_INET, SOCK_STREAM, 0) ) < 0 )
ErrorAndExit("Could not create socket");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(IP);
serv_addr.sin_port = htons(PORT);
if( (bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) ) < 0 )
ErrorAndExit("Could not bind on Given IP");
if( (listen(listenfd, 10) ) < 0 )
ErrorAndExit("Could not listen");
if( ( connfd = accept(listenfd, (struct sockaddr*)NULL, NULL) ) < 0 )
ErrorAndExit("Could not accept");
write(connfd, "Server Message", strlen("Server Message"));
close(connfd);
return 0;
}
void ErrorAndExit(const char *str)
{
printf("Error : %s\n", str);
exit(EXIT_FAILURE);
}
|