-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathminibbd.c
76 lines (63 loc) · 1.46 KB
/
minibbd.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
69
70
71
72
73
74
75
76
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <winsock2.h>
#include <stdio.h>
int main(int argc, char **argv)
{
char *addr;
int port;
char recvbuf[32000];
int bytesRecv;
int m;
int s;
struct sockaddr_in service;
// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR)
printf("Error at WSAStartup()\n");
if (argc > 2) port = atoi(argv[2]);
else port = 1984;
if (argc > 1) addr = argv[1];
else addr = "0.0.0.0";
// Create a socket.
m = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m == -1) {
printf("Error at socket(): %d\n", WSAGetLastError());
WSACleanup();
return 0;
}
// Bind the socket.
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(addr);
service.sin_port = htons(port);
if (bind(m, (struct sockaddr *)&service, sizeof(service)) == -1) {
printf("bind() failed.\n");
closesocket(m);
return 0;
}
// Listen on the socket.
if (listen(m, 1) == -1)
printf("Error listening on socket.\n");
// Accept connections.
for (;;) {
printf("Waiting for a client to connect...\n");
while (1) {
s = -1;
while (s == -1) {
s = accept(m, NULL, NULL);
}
printf("Client Connected.\n");
break;
}
// Send and receive data.
bytesRecv = recv(s, recvbuf, sizeof recvbuf, 0);
printf("Bytes Recv: %d\n", bytesRecv);
if (bytesRecv > 0) {
fwrite(recvbuf, 1, bytesRecv, stdout);
fflush(stdout);
}
closesocket(s);
}
return 0;
}