Форум программистов, компьютерный форум, киберфорум
C++: Сети
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.89/18: Рейтинг темы: голосов - 18, средняя оценка - 4.89
0 / 0 / 1
Регистрация: 11.06.2012
Сообщений: 3

Как взаимодействуют клиент-сервер в готовой программе(сокеты)

11.06.2012, 04:01. Показов 3297. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Скачал курсовую "Комплекс сетевой защиты".
2 программы клиент(raw_send) - сервер (raw_recv).
в вложенном архиве raw.zip: 2 экзешника и 2 их файла-настройки: pop3_conf.inf к raw_recv, http_conf.inf к raw_send. и кратенькая пояснительная записка.
Не могу разобраться как они должны взаимодействовать. (ниже жирным)
Сервер (Raw_RECV): 2 потока:
1) отлавливает пакеты (вирусы) - все работает, вопросов нет.
2) "Waiting for a POP3 connection..." ждет подключение клиента (ну и дальше работа с почтой)
вот моя главная проблема - никак никакой клиент не подключается...
должен ли имено Raw-send к нему подключаться? как правильно должны быть заполнены файлики-конфиги? ип? порты? Можно ли на одном ПК? Обязательно ли наличие интернета/локалки? или какой клиент ему нужен?

Клиент (raw_send): должен ли он коннектится к серверу? о нем в "вкратце.doc"
что я понял: что он - генератор пакетов (имитирует сетевые атаки(для проверки сервера)) через http запросы. (ну т.е. есть htm файлики на которых можно выбирать тип атаки, ип)
а само консольное окно никак не активно.
на всякий случай еще выложил листинг, там весь код прокоментирован

Скорей всего там все написано, всё есть и всё должно работать, просто я не понимаю как должно работать
понимаю вопрос слишком глобальный, но хоть в каком направлении копать)
Вложения
Тип файла: zip raw.zip (190.5 Кб, 42 просмотров)
Тип файла: zip листинг.zip (76.8 Кб, 37 просмотров)
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
11.06.2012, 04:01
Ответы с готовыми решениями:

Низкоуровневые сокеты (ICMP протокол), Ошибка с типами, Клиент-Сервер
Создать для клиента генератор пакетов (для проведения атаки ICMP-Flood), а для сокета-сервера чтение с защитой. При компиляции...

Клиент-Серверное приложение. Как сделать, чтобы сервер сам отправлял сообщения на клиент
Добрый день всем. Проблема заключается в следующем: Есть клиент-серверное приложение, хочу реализовать своего рода защиту, чтобы при...

Реализация чата Клиент - Клиент (сокеты)
Разобрался с созданием сокетов: инициализация, создание(ну или не разобрался =(( ). Не понял суть функции accept и установку соединения. ...

2
0 / 0 / 1
Регистрация: 11.06.2012
Сообщений: 3
11.06.2012, 04:13  [ТС]
ах да задав поиск "connect" в коде клиента, такой функции не было найдено (по идее имено она коннектит клиент к серверу). Была только int accept_connect(void);
насчет листинга: там много юнитов и много кода - и я подумал что будет слишком громоздко сюда выкладывать или норм?
0
0 / 0 / 1
Регистрация: 11.06.2012
Сообщений: 3
13.06.2012, 13:10  [ТС]
Лучший ответ Сообщение было отмечено 1As1 как решение

Решение

Скоро уже сдавать, помогите разобраться)) а то я даже не знаю нужно что дописывать или нет)
Вообще по идее какие должны быть айпи у клиента и сервера указаны? и порты?

Сервер(raw-recv):
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
///////////////////////////////////
RAW_RECV.CPP
///////////////////////////////////
 
#include "packet.h"
#include "server.h"
 
int pack_num=0;
char StartPathGlobal[MAX_PATH]={0};
 
int make_message(char* filename);
 
int main(void)
{
    WSADATA        wsd;
    
    DWORD dwThreadID_POP3;
 
    printf("The ICMP-based Network Intrusion Detection System.\n\n");
 
    if (getcwd(StartPathGlobal,MAX_PATH)==NULL) 
    {cout<<"Server could not retrieve its pathname on startup.";return -1;}
    
    if (StartPathGlobal[strlen(StartPathGlobal)-1]!='\\') 
    strcat(StartPathGlobal,"\\");
 
    // Load Winsock
        
    if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) 
    {
        printf("WSAStartup failed!\n");getchar();
        return 1;
    }
 
    if (CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFuncPOP3,
    0,0,&dwThreadID_POP3)==NULL) 
    cout<<GetLastError()<<endl;
 
    // Creating a raw socket
        
    RAW_SOCKET    raw_socket(IPPROTO_ICMP);
 
    raw_socket.BindSocket(htonl(INADDR_ANY)); //inet_addr(szInterface);
 
    raw_socket.RecvPackets();
    
    closesocket(raw_socket.s);
 
    WSACleanup();
    getchar();
    return 0;
}
 
int RAW_SOCKET::RecvPackets(void)
{
   
    char  buf[MAX_ICMP_PACKET]={0};
    int          iSenderSize;
    SOCKADDR_IN  sender;
    int            ret,j;
 
    ZeroMemory(buf,MAX_ICMP_PACKET);
    
    // Read the datagrams
    
    printf("Waiting for incoming packets...\n\n");
 
//  for(i = 0; i < iCount; i++)
    while(1)
    {
        iSenderSize = sizeof(sender);
        ret = recvfrom(s, buf, MAX_ICMP_PACKET, 0, 
                (SOCKADDR *)&sender, &iSenderSize);
          
 
        if (ret == SOCKET_ERROR)
        {
            printf("recvfrom() failed; %d\n", WSAGetLastError());getchar();
            break;
        }
        else if (ret == 0)
            break;
        else
        {
            buf[ret] = '\0';
            
            ((ICMP_PACKET*)buf)->PrintPacket();
 
            printf("Info received from [%s]:\n", inet_ntoa(sender.sin_addr));
            for (j=0;j<ret;j++) printf("%d", buf[j]);
            printf("%c",'\n');
            for (j=0;j<ret;j++) printf("%c", buf[j]);
            printf("%c",'\n');
            printf("Number of bytes received: %d\n", ret);
 
            ((ICMP_PACKET*)buf)->DetectAttack();
        }
    }
 
return 0; 
};
 
int ICMP_PACKET::DetectAttack(void)
{
IP_HDR             ipHdrRef;
ICMP_HDR           icmpHdrRef;
struct in_addr     addrRef;
 
ZeroMemory(&ipHdrRef,sizeof(ipHdrRef));
ZeroMemory(&icmpHdrRef,sizeof(icmpHdrRef));
ZeroMemory(&addrRef,sizeof(addrRef));
 
memcpy(&ipHdrRef, buf, sizeof(ipHdrRef)); 
memcpy(&icmpHdrRef, (buf + sizeof(ipHdrRef)), sizeof(icmpHdrRef));
 
addrRef.S_un.S_addr = ipHdrRef.ip_destaddr;
 
if (!strcmp(inet_ntoa(addrRef),"127.0.0.255")) 
{
cout<<"The Smurf attack detected !"<<endl;
make_message("smurf.txt");
}
 
if (icmpHdrRef.i_code == 3) 
{
cout<<"The Tribe Flood Network attack detected !"<<endl;
make_message("tribeflood.txt");
}
 
if (icmpHdrRef.i_code == 5) 
{
cout<<"The WinFreeze attack detected !"<<endl;
make_message("winfreeze.txt");
}
 
if (icmpHdrRef.i_code == 2)
{
pack_num++;
}
 
if (pack_num==100) 
{
pack_num=0;
cout<<"The ICMP Flood attack detected !"<<endl;
make_message("icmpflood.txt");
}
 
return 0;
};
 
int make_message(char* filename)
{
 
char source_path[MAX_PATH]={0}, dest_path[MAX_PATH]={0};
fstream source_file,dest_file;
char ch;
 
ZeroMemory(source_path,MAX_PATH); ZeroMemory(dest_path,MAX_PATH);
strcpy(source_path,StartPathGlobal); strcpy(dest_path,StartPathGlobal);
 
strcat(source_path,"storage\\"); strcat(source_path,filename);
strcat(dest_path,"attacks\\"); strcat(dest_path,filename);
 
source_file.open(source_path,ios::in|ios::binary);
dest_file.open(dest_path,ios::out|ios::binary);
 
while (!source_file.eof()) 
{
source_file.read(&ch,1);
dest_file.write(&ch,1);
}
 
source_file.close();
dest_file.close();
 
return 0;
};
 
///////////////////////////////////
packet.h
///////////////////////////////////
 
#pragma pack(1)
 
#define WIN32_LEAN_AND_MEAN   // Windows Headers use this symbol 
// to exclude rarely-used header files. Please refer to Windows.H 
//to determine the files that will be excluded when this symbol is defined
 
#include <winsock2.h>
#include <ws2tcpip.h>
 
#include <stdio.h>
#include <stdlib.h>
 
#define MAX_MESSAGE        4068
#define MAX_PACKET         4096
#define ICMP_ECHO          8
#define MAX_ICMP_PACKET    1024      // Max ICMP packet size
 
//
// Setup some default values 
//
#define DEFAULT_PORT_SEND       //5001
//#define DEFAULT_PORT_RECV       5000
//#define DEFAULT_IP_SEND        "127.0.0.1"
//#define DEFAULT_IP_RECV        "127.0.0.1"
//#define DEFAULT_COUNT           1 //5
#define DEFAULT_MESSAGE    "This is a test"
//char  szInterface[32] = "10.0.0.1";  // Default interface to read datagrams from
 
//
// Define the IP header. Make the version and length field one
// character since we can't declare two 4 bit fields without
// the compiler aligning them on at least a 1 byte boundary.
//
typedef struct ip_hdr
{
    u_char  ip_verlen;        // IP version & length
    u_char  ip_tos;           // IP type of service
    u_short ip_totallength;   // Total length
    u_short ip_id;            // Unique identifier 
    u_short ip_offset;        // Fragment offset field
    u_char  ip_ttl;           // Time to live
    u_char  ip_protocol;      // Protocol(TCP,UDP etc)
    u_short ip_checksum;      // IP checksum
    u_int   ip_srcaddr;       // Source address
    u_int   ip_destaddr;      // Destination address
} IP_HDR, *PIP_HDR, FAR* LPIP_HDR;
//
// Define the UDP header 
//
typedef struct udp_hdr
{
    u_short src_portno;       // Source port number
    u_short dst_portno;       // Destination port number
    u_short udp_length;       // UDP packet length
    u_short udp_checksum;     // UDP checksum (optional)
} UDP_HDR, *PUDP_HDR;
 
typedef struct icmp_hdr 
{
    BYTE   i_type;
    BYTE   i_code;                 // Type sub code
    USHORT i_cksum;
    USHORT i_id;
    USHORT i_seq;
} ICMP_HDR, *PICMP_HDR;
 
u_short checksum(u_short *buffer, int size);
 
typedef struct tag_param{char name[100];} PARAM;
 
//////////////////////////////////////////////////////////////////////////
 
class ICMP_PACKET
{
public:
char    buf[MAX_PACKET],*ptr;
    
IP_HDR    ipHdr;
ICMP_HDR  icmpHdr;
u_short iTotalSize;
struct sockaddr_in remote;       // IP addressing structures
 
void PrintPacket(void);
void FillFields(PARAM* param);
int DetectAttack(void);
};
 
class RAW_SOCKET
{
public:
SOCKET    s;
BOOL      bOpt;
RAW_SOCKET(int proto);
int SendPackets(char* buf, u_short TotalSize, 
            struct sockaddr_in *p_remote, DWORD amount);
int BindSocket(u_long address);
int RecvPackets(void);
};
 
int send_icmp_sequence(PARAM* param);
 
///////////////////////////////////
server.h
///////////////////////////////////
 
#include <fstream>
#include <iostream>
#include <winsock2.h>
#include <time.h>
#include <conio.h>
#include <direct.h>
#include <stdio.h>
#include <io.h>
#define MAX_CONNECTIONS 5
#define SIZE_OF_BUFFER 128  
 
#define ADDRESS_MAX_LENGTH 64
#define MAX_USERS 10
 
using namespace std;
 
typedef struct tag_file // структура - описатель файла-письма
{
char filename[MAX_PATH];
int filesize;
bool del; // признак удаления
} FILE_REF;
 
//////////////////////////////////////////////////////////////////////////
 
class MODE // режим соединения (для нормальной работы с Outlook Express
// этот класс не нужен, я его сделал ,чтобы быть ближе к RFC 1225)
{
public:
bool authorization_mode;
bool transaction_mode;
bool update_mode;
MODE();
void SetAuthorizationMode(void);
void SetTransactionMode(void);
void SetUpdateMode(void);
bool IsAuthorizationMode(void);
bool IsTransactionMode(void);
bool IsUpdateMode(void);
};
 
//////////////////////////////////////////////////////////////////////////
 
typedef struct tag_user
{ // для адреса "box@mailserver1.com" запишем:
char name[ADDRESS_MAX_LENGTH]; // сюда "box"
char domain[ADDRESS_MAX_LENGTH]; // сюда "mailserver1.com"
char password[ADDRESS_MAX_LENGTH]; // сюда пароль
bool lock; // заперт ли почтовый ящик
} USER;
 
//////////////////////////////////////////////////////////////////////////
 
class CONF // здесь содержится вся конфигурация POP3-сервера
    { 
    public:
    fstream conf_file; // из этого файла при запуске программы считываем 
    // настройки SMTP-сервера
    char ip_address[32]; // ip-адрес этого сервера
    int port; //порт, на который будем принимать POP3-запросы (обычно 110)
    int echo; // выводить ли на экран каждое действие
 
    char Path[MAX_PATH]; // путь к исполняемому файлу сервера
    char Domain[ADDRESS_MAX_LENGTH]; // домен сервера (напр. "mailserver1.com")
    // если мы получаем письмо в Outlook Express'е на адрес 
    //"box@mailserver1.com", то содержимым "Domain" будет "mailserver1.com"
 
 
    FILE_REF file[MAX_USERS]; // массив описателей для файлов - писем
    int f_index; // его индекс
    int highest_number_accessed; // непонятная хрень, смотрите RFC 1225
    int c_mes; // номер обрабатываемого файла-письма для соответствующих команд
    int total_size; // суммарный размер файлов-писем в почтовом ящике
 
    CONF(void);
    void Init(void); // считать настройки сервера из файла "conf.inf"
    void ProcessConfigCommands(void); // обработать команды настройки сервера
    int ParseMailDrop(char* user); // название функции навеяно RFC 1225.
    // функция просматривает почтовый ящик, идентифицирует отдельные 
    // файлы-письма, определяет размер каждого и общий их размер
 
    // 7 функций для работы с пользователями
    // кстати, "пользователь" - это папка с файлом "password.inf"
    bool IsUserExistent(char* User);
    int DeleteUser(void);
    int AddUser(void);
    void Help(void);
    int ListUsers(void);
    char* GetPassword(char* user,char* password);
    void SetPassword(void);
    };
 
//////////////////////////////////////////////////////////////////////////
 
class DISPATCH_SERVER_SOCKET
{
public:
long connection_time;
struct sockaddr_in server_address,client_address;
int retval,size_of_client_address;
WSADATA wsaData;
SOCKET dispatch_server_socket, msg_server_socket;
DWORD dwThreadID;
DISPATCH_SERVER_SOCKET(CONF& conf);
CONF conf;
int accept_connect(void);
};
 
//////////////////////////////////////////////////////////////////////////
 
class SERVER_SOCKET
{
public:
char Buffer[SIZE_OF_BUFFER];
SOCKET msg_server_socket;
 
int query; // флаг, который разрешает/запрещает ответ на запрос
int quit; // флаг, который показывает, что сеанс почтовой связи окончен
 
CONF conf;
long connection_time;
fstream report_file; // в этот файл запишем всё, что сервер получает 
// и отправляет
 
USER user; // почтовый ящик, из которого мы забираем почту за одно 
// подключение. Для обращения к каждому почтовому ящику клиент всегда 
// создаёт новое подключение, даже если эти ящики находятся на одном
// сервере. 
 
char forward_path[ADDRESS_MAX_LENGTH];
char reverse_path[ADDRESS_MAX_LENGTH];
fstream mes_file; // сюда записываем сообщение, пришедшее серверу 
// за 1 почтовую транзакцию с клиентом. Может фактически содержать в себе 
// несколько e-mail'ов
char mes_path[MAX_PATH]; // уник. имя файла - сообщения
MODE mode;
int not_this_command; // счётчик нераспознавания принятой команды
 
 
SERVER_SOCKET(void);
int recv_data(void);
int send_data(void);
int shutdown_and_closesocket(void);
void erase_buffer(void);
void set_buffer(char*);
int ReplyOnClientConnection(void); // послать ответ клиенту на 
// его подключение
int ProcessClientQuery(void); // обработать запрос клиента
SERVER_SOCKET& operator=(SERVER_SOCKET& right);
};
 
//////////////////////////////////////////////////////////////////////////
 
DWORD WINAPI ThreadFunc(SERVER_SOCKET* p_server_socket);
// нить, запускаемая при подключении клиента
 
char* getspos(char* search_string,char search_symbol);
// получить указатель на первое вхождение символа в строке
char* substring(char* st,char s1,char s2,char* ret);
// извлечь в ret подстроку из st, заключённую между символами s1 и s2
// (не включая s1 и s2 в возвращаемое значение)
void readcomment(fstream& file); // считать и выбросить комментарий 
// из файла "conf.inf"
 
//////////////////////////////////////////////////////////////////////////
 
DWORD WINAPI ThreadFuncPOP3(void);
 
///////////////////////////////////
server.cpp
///////////////////////////////////
 
/* При компилировании необходимо: 
   1.) Добавить в Project/Settings/Link/Object/library modules  ws2_32.lib.
   2.) Изменить в Project/Settings/С/С++/Category:Code Generation для
   Settings For: Win32 Debug в пункте Use run-time library 
   Debug Single-Threaded на Debug Multithreaded.
*/
 
#include "server.h"
 
//////////////////////////////////////////////////////////////////////////
 
DISPATCH_SERVER_SOCKET::DISPATCH_SERVER_SOCKET(CONF& conf_ref)
{
// Инициализируем библиотеку WS2_32.DLL
if ((retval = WSAStartup(0x202,&wsaData)) != 0) 
    {cerr<<"WSAStartup failed with error "<<retval<<endl;
    getch();WSACleanup();exit(-1);}
 
size_of_client_address = sizeof(client_address);
 
// Создаём базовый(диспетчерский) сокет сервера, настроенный на TCP
dispatch_server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 
if (dispatch_server_socket == INVALID_SOCKET)
    {cerr<<"socket() failed with error "<<WSAGetLastError()<<endl;
getch();WSACleanup();exit(-1);} 
 
// Записываем в адресную структуру IP адрес сервера и порт сервера
server_address.sin_family = AF_INET;
server_address.sin_port = htons(conf_ref.port);//Port MUST be in Network Byte Order
server_address.sin_addr.S_un.S_addr = inet_addr (conf_ref.ip_address);
 
// Связываем адрес сервера с базовым(диспетчерским) сокетом сервера
if (bind(dispatch_server_socket,(SOCKADDR*) &server_address, 
         sizeof(server_address))==SOCKET_ERROR)
    {cerr<<"bind() failed with error "<<WSAGetLastError()<<endl;
    getch();WSACleanup();exit(-1);}
 
// Переводим базовый(диспетчерский) сокет сервера на режим 
// прослушивание/диспетчеризация сигналов на подключение и устанавливаем 
// размер очереди одновременных обращений к серверу
if (listen(dispatch_server_socket,MAX_CONNECTIONS)==SOCKET_ERROR)
    {cerr<<"listen() failed with error "<<WSAGetLastError()<<endl;
    getch();WSACleanup();exit(-1);}
 
conf=conf_ref;
}
 
//////////////////////////////////////////////////////////////////////////
 
int DISPATCH_SERVER_SOCKET::accept_connect(void)
{
//cout<<"Waiting for a client's connection..."<<endl<<endl;
cout<<"Waiting for a POP3-connection..."<<endl<<endl;
 
//************************************************************************
while (true)
{
// Ждём очередное подключение к серверу (функцией connect()) клиента и, 
// дождавшись, возвращаем виртуальный сокет сервера - для двухстороннего 
// обмена сообщениями с данным клиентом
    msg_server_socket = accept(dispatch_server_socket,
                    (SOCKADDR*) &client_address, &size_of_client_address); 
 
// Если случилась ошибка ожидания клиента (кроме отсутствия вызова клиента), то:
if (msg_server_socket==INVALID_SOCKET)
    {cerr<<"accept() failed with error "<<WSAGetLastError()<<endl;
    // Закрываем базовый(диспетчерский) сокет сервера
    if (closesocket(dispatch_server_socket)==SOCKET_ERROR)
    cerr<<"closesocket() failed with error "<<WSAGetLastError()<<endl;
    WSACleanup();return 0;}
 
// Выводим на экран время подключения клиента, его IP-адрес и порт
if ( client_address.sin_family == AF_INET) // если это TCP-клиент,то:
{
    connection_time=time(0);
    cout<<"Accepted POP3-connection on: "<<ctime(&connection_time)
    <<"from IP address: "<<inet_ntoa(client_address.sin_addr)<<" port: "
    <<ntohs(client_address.sin_port)<<endl<<endl;
}
 
// Для каждого подключившегося клиента создаём нить и передаём в неё
// адрес виртуального сокета сервера для двухстороннего 
// обмена сообщениями с данным клиентом (нити нужны здесь для того, чтобы
// позволить серверу работать одновременно с несколькими клиентами)
SERVER_SOCKET server;
server.msg_server_socket = msg_server_socket;
server.connection_time = connection_time;
server.conf=conf;
 
if (CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunc,
    (LPVOID)&server,0,&dwThreadID)==NULL) 
    cout<<GetLastError()<<endl;
}// end of while
//************************************************************************
 
// Закрываем базовый(диспетчерский) сокет сервера
    if (closesocket(dispatch_server_socket)==SOCKET_ERROR)
    cerr<<"closesocket() failed with error "<<WSAGetLastError()<<endl;
 
// Освобождаем ресурсы с помощью библиотеки WS2_32.DLL
WSACleanup();
return 0;
};
 
 
SERVER_SOCKET::SERVER_SOCKET(void)
{
erase_buffer();
 
quit = 0;// Нужно ли закончить сеанс связи
connection_time = 0;
query = 0; // флаг, который разрешает/запрещает запрос
not_this_command=0;
 
ZeroMemory(&user,sizeof(user));
ZeroMemory(forward_path,sizeof(forward_path));
ZeroMemory(reverse_path,sizeof(reverse_path));
ZeroMemory(mes_path,sizeof(mes_path));
};
 
 
int SERVER_SOCKET::shutdown_and_closesocket(void)
{
cout<<"Terminating POP3-connection."<<endl<<endl;
 
// Блокируем получение - отправку сообщений у виртуального сокета сервера
if (shutdown(msg_server_socket,SD_BOTH)==SOCKET_ERROR) 
{cerr<<"shutdown() failed with error "<<WSAGetLastError()<<endl;return -1;}
 
// Закрываем виртуальный сокет сервера, связанный с данным клиентом
if (closesocket(msg_server_socket)==SOCKET_ERROR) 
{cerr<<"closesocket() failed with error "<<WSAGetLastError()<<endl;
return -1;}
return 0;
};
 
void SERVER_SOCKET::erase_buffer(void)
{
ZeroMemory(&Buffer,sizeof(Buffer));
}
 
 
void SERVER_SOCKET::set_buffer(char* string)
{
erase_buffer();
strcpy(Buffer,string);
}
 
 
int SERVER_SOCKET::recv_data(void)
{
erase_buffer();
 
// Ждём приёма сообщения от клиента
char ch;
int retval;
char S[]={"S: "};
 
for (int i=0; i<sizeof(Buffer); i++)
{
// Принимаем побайтно то, что клиент отправил как цельное сообщение
// (для того, чтобы мы могли распознавать отдельные команды)
retval = recv(msg_server_socket,&ch,sizeof(char),0 );
if (retval == SOCKET_ERROR) 
    {cerr<<"recv() failed: error "<<WSAGetLastError()<<endl;
    closesocket(msg_server_socket); return -1;}
 
else {Buffer[i]=ch; if (ch =='\n') break;};
};      
if(conf.echo)
cout<<"S:  "<<Buffer<<endl;
 
report_file.write(S,strlen(S));
report_file.write(Buffer,strlen(Buffer));
 
return 0;
};
 
//////////////////////////////////////////////////////////////////////////
 
int SERVER_SOCKET::send_data(void)
{
int retval;
char R[]={"R: "};
 
retval = send(msg_server_socket,Buffer,strlen(Buffer),0); // ни в коем 
                                           // случае не sizeof(Buffer)
if (retval == SOCKET_ERROR) 
    {cerr<<"send() failed: error "<<WSAGetLastError()<<endl;return -1;}
 
if(conf.echo)
cout<<"R:  "<<Buffer<<endl;
 
report_file.write(R,strlen(R));
report_file.write(Buffer,strlen(Buffer));
erase_buffer();
return 0;
};
 
//////////////////////////////////////////////////////////////////////////
 
char* substring(char* st,char s1,char s2,char* ret)
{
ZeroMemory(ret,sizeof(ret));
strncpy(ret,getspos(st,s1)+1,getspos(st,s2)-getspos(st,s1)-1);
return ret;
}
 
//////////////////////////////////////////////////////////////////////////
 
char* getspos(char* search_string,char search_symbol)
{
int count=0;
 
while(true)
{
if (count>100) 
{
cout<<"The search symbol "<<search_symbol<<"was not found."<<endl;
getch();return NULL;
}
if (*search_string != search_symbol) 
{search_string++; count++;} else break;
}// endwhile
 
return search_string;
}
 
//////////////////////////////////////////////////////////////////////////
 
SERVER_SOCKET& SERVER_SOCKET::operator=(SERVER_SOCKET& right)
{
if (&right!=this)
{
msg_server_socket = right.msg_server_socket;
connection_time = right.connection_time;
conf=right.conf;
}
return *this;
}
 
///////////////// Описание конфигурационного объекта /////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
 
bool CONF::IsUserExistent(char* User)
{
bool ret=false;
char temp_path[MAX_PATH]={0};
strcpy(temp_path,Path);
strcat(temp_path,"\\");
strcat(temp_path,User);
 
if (!chdir(temp_path)) ret=true;
if (chdir(Path)) {cout<<"MainPath not found."<<endl; return false;}
return ret;
}
 
//////////////////////////////////////////////////////////////////////////
 
int CONF::ListUsers(void)
{
{
WIN32_FIND_DATA file_info;
HANDLE file_handle;
char filename[MAX_PATH]={0};
 
strcpy(filename,Path);
strcat(filename,"\\*"); // текущая директория
 
file_handle = FindFirstFile((LPSTR)filename,&file_info);
if (file_handle==INVALID_HANDLE_VALUE) 
    {cout<<"FindFirstFile failed with error: "<<GetLastError()<<endl;
    return -1;}
else 
{
if(file_info.dwFileAttributes==FILE_ATTRIBUTE_DIRECTORY&&
   strcmp(file_info.cFileName,".")&&strcmp(file_info.cFileName,".."))
cout<<file_info.cFileName;
 
while(FindNextFile(file_handle,&file_info))
if(file_info.dwFileAttributes==FILE_ATTRIBUTE_DIRECTORY&&
   strcmp(file_info.cFileName,".")&&strcmp(file_info.cFileName,".."))
cout<<endl<<file_info.cFileName;
 
FindClose(file_handle);cout<<endl;
return 0;}
}}
 
//////////////////////////////////////////////////////////////////////////
 
int CONF::AddUser(void)
{
char temp_path[MAX_PATH]={0},User[MAX_PATH]={0};
strcpy(temp_path,Path);
strcat(temp_path,"\\");
 
cin>>User;
strcat(temp_path,User);
 
if (mkdir(temp_path)==-1) 
{cout<<"The new mailbox was not created."<<endl;return -1;}
cout<<endl<<"The mailbox \""<<User<<"\" was successfully created."<<endl;
 
return 0;
}
 
//////////////////////////////////////////////////////////////////////////
 
int CONF::DeleteUser(void)
{
char temp_path[MAX_PATH]={0},User[MAX_PATH]={0},
FilePath[MAX_PATH]={0},filename[MAX_PATH]={0};
 
WIN32_FIND_DATA file_info;
HANDLE file_handle;
 
strcpy(temp_path,Path);
strcat(temp_path,"\\");
 
cin>>User;
strcat(temp_path,User);
 
strcpy(filename,temp_path);
strcat(filename,"\\*"); // текущая директория
 
file_handle = FindFirstFile((LPSTR)filename,&file_info);
if (file_handle==INVALID_HANDLE_VALUE) 
    {cout<<"FindFirstFile failed with error: "<<GetLastError()<<endl;
    return -1;}
else 
{
strcpy(FilePath,temp_path);
strcat(FilePath,"\\");
strcat(FilePath,file_info.cFileName);
remove(FilePath);
 
while(FindNextFile(file_handle,&file_info))
{
strcpy(FilePath,temp_path);
strcat(FilePath,"\\");
strcat(FilePath,file_info.cFileName);
remove(FilePath);
}
 
FindClose(file_handle);cout<<endl;
}
 
if (rmdir(temp_path)==-1) 
{cout<<"The mailbox was not deleted."<<endl;return -1;}
cout<<endl<<"The mailbox \""<<User<<"\" was successfully deleted."<<endl;
 
return 0;
}
 
//////////////////////////////////////////////////////////////////////////
 
void readcomment(fstream& file)
{
char empty[MAX_PATH]={0}; // буфер для считывания
ZeroMemory(empty,sizeof(empty));
file.getline(empty,sizeof(empty),10);
}
 
//////////////////////////////////////////////////////////////////////////
 
void CONF::Init(void)
{
fstream empty_file;
 
conf_file.open("pop3_conf.inf",ios::in);
conf_file>>Domain;
readcomment(conf_file);
conf_file>>ip_address; 
readcomment(conf_file);
conf_file>>port;
readcomment(conf_file);
conf_file>>echo;
readcomment(conf_file);
 
conf_file.close();
 
if (getcwd(Path,MAX_PATH)==NULL) 
{cout<<"Current path was not found."<<endl;getch();}
 
empty_file.open("pop3_report.txt",ios::trunc);
empty_file.close();
 
};
 
//////////////////////////////////////////////////////////////////////////
 
void CONF::ProcessConfigCommands(void)
{
char command[MAX_PATH]={0};
 
while (true)
{
cout<<"command: ";
cin>>command;
if(!strncmp(command,"start",5)) {cout<<endl; break;}
else if(!strncmp(command,"help",4)) {Help();cout<<endl;}
else if(!strncmp(command,"'",1)) {cout<<endl; break;}
else if(!strncmp(command,"exit",4)) {cout<<endl; exit(0);}
else if(!strncmp(command,"list",5)) {ListUsers(); cout<<endl;}
else if(!strncmp(command,"adduser",5)) {AddUser(); cout<<endl;}
else if(!strncmp(command,"deluser",5)) {DeleteUser();cout<<endl;}
 
// то, что дублируется конфигурационным файлом, загружаемым в начале 
// работы программы
else if(!strncmp(command,"getdom",6)) 
{cout<<"The domain name is: \""<<Domain<<"\""<<endl<<endl;}
 
else if(!strncmp(command,"chdom",5)) {cin>>Domain;
cout<<"The new domain name is: \""<<Domain<<"\""<<endl<<endl;}
 
else if(!strncmp(command,"getip",5)) 
{cout<<"The assigned ip-address of this POP3-server is: \""
<<ip_address<<"\""<<endl<<endl;}
 
else if(!strncmp(command,"chip",4)) {
cin>>ip_address;
if(!strcmp(ip_address,"0")) 
{ZeroMemory(ip_address,sizeof(ip_address));
    strcpy(ip_address,"0.0.0.0");}
cout<<"The newly assigned ip-address of this POP3-server is: \""
<<ip_address<<"\""<<endl<<endl;}
 
else if(!strncmp(command,"getport",7)) 
{cout<<"The POP3-accept port is: \""<<port<<"\""<<endl<<endl;}
 
else if(!strncmp(command,"chport",6)) {cin>>port;
cout<<"The new POP3-accept port is: \""<<port<<"\""<<endl<<endl;}
 
else if(!strncmp(command,"getpswd",7)) {
char i_user[ADDRESS_MAX_LENGTH]={0},i_password[ADDRESS_MAX_LENGTH]={0};
cin>>i_user;
cout<<"The password for the user \""<<i_user<<"\" is: "
<<GetPassword(i_user,i_password)<<endl;}
 
else if(!strncmp(command,"chpswd",6)) {SetPassword(); cout<<endl;}
    
else cout<<endl<<"unknown command."<<endl<<endl;
}//endwhile
};
 
//////////////////////////////////////////////////////////////////////////
 
void CONF::Help(void)
{
cout<<endl;
cout<<"list - see all existent mailboxes"<<endl;
cout<<"start - start the POP3-server"<<endl;
cout<<"exit - exit from the program"<<endl;
cout<<"adduser <new_user> - create a new mailbox"<<endl;
cout<<"deluser <user> - delete a mailbox"<<endl;
cout<<"getdom - print this server's domain name"<<endl;
cout<<"chdom <new_domain> - reassign the new domain name to this server"
<<endl;
 
cout<<"getip - print the ip-address to be assigned to this POP3-server"
<<endl<<'\t'<<"on this server's startup"<<endl;
 
cout<<"chip <new_ip-address> - input new ip-address to be assigned "<<endl
<<"to this POP3-server on this server's startup"<<endl;
 
cout<<"getport - print this server's POP3-accept port"<<endl;
cout<<"chport <new_port> - reassign the new POP3-accept port to this \
server"<<endl;
 
cout<<"getpswd <user> - print this user's password"<<endl;
cout<<"chpswd <user> <new_password> - set new password to this user"<<endl;
 
cout<<"help - get this help"<<endl;
}
 
//////////////////////////////////////////////////////////////////////////
 
CONF::CONF(void)
{
ZeroMemory(ip_address,sizeof(ip_address));
ZeroMemory(Path,sizeof(Path));
ZeroMemory(Domain,sizeof(Domain));
port=0;
echo=false;
ZeroMemory(file,sizeof(file));
f_index=0;
highest_number_accessed=0;
c_mes = 0;
total_size = 0;
};
 
//////////////////////////////////////////////////////////////////////////
 
char* CONF::GetPassword(char* user,char* password)
{
char temp_path[MAX_PATH]={0};
fstream passw_file;
 
strcpy(temp_path,Path);
strcat(temp_path,"\\");
strcat(temp_path,user);
strcat(temp_path,"\\");
strcat(temp_path,"password.inf");
passw_file.open(temp_path,ios::in);
passw_file>>password;
passw_file.close();
 
return password;
};
 
//////////////////////////////////////////////////////////////////////////
 
void CONF::SetPassword(void)
{
char temp_path[MAX_PATH]={0}, password[ADDRESS_MAX_LENGTH]={0},
user[ADDRESS_MAX_LENGTH]={0};
fstream passw_file;
cin>>user>>password;
 
strcpy(temp_path,Path);
strcat(temp_path,"\\");
strcat(temp_path,user);
strcat(temp_path,"\\");
strcat(temp_path,"password.inf");
passw_file.open(temp_path,ios::out);
passw_file<<password;
passw_file.close();
cout<<"The new password for the user \""<<user<<"\" is: "<<password<<endl;
};
 
///////////////////////////////////
packet.cpp
///////////////////////////////////
 
#include "packet.h"
 
void ICMP_PACKET::PrintPacket(void)
{
    IP_HDR             ipHdrRef;
    ICMP_HDR           icmpHdrRef;
    struct in_addr     addrRef;
 
    printf("Prepared to send: %d bytes\n", iTotalSize);
    
    ZeroMemory(&ipHdrRef,sizeof(ipHdrRef));
    ZeroMemory(&icmpHdrRef,sizeof(icmpHdrRef));
    ZeroMemory(&addrRef,sizeof(addrRef));
 
    memcpy(&ipHdrRef, buf, sizeof(ipHdrRef)); 
    memcpy(&icmpHdrRef, (buf + sizeof(ipHdrRef)), sizeof(icmpHdrRef));
 
 
    printf("The IP-header content:\n\n");
 
    printf("Type of service: %d\n", ipHdrRef.ip_tos);
    printf("Total packet length: %d\n", ntohs(ipHdrRef.ip_totallength));
    printf("Unique identifier: %d\n", ntohs(ipHdrRef.ip_id));
    printf("Fragment offset field: %d\n", ntohs(ipHdrRef.ip_offset));
    printf("Time to live: %d\n", ipHdrRef.ip_ttl);
    printf("Encapsulated protocol number: %d\n", ipHdrRef.ip_protocol);
    printf("Checksum: %d\n", ntohs(ipHdrRef.ip_checksum));
    addrRef.S_un.S_addr = ipHdrRef.ip_srcaddr;
    printf("Source address: %s\n", inet_ntoa(addrRef));
    ZeroMemory(&addrRef,sizeof(addrRef));
    addrRef.S_un.S_addr = ipHdrRef.ip_destaddr;
    printf("Destination address: %s\n\n", inet_ntoa(addrRef));
    
    printf("The ICMP-header content:\n\n");
    
    printf("Type: %d\n", icmpHdrRef.i_type);
    printf("Code: %d\n", icmpHdrRef.i_code);
    printf("Checksum: %d\n", ntohs(icmpHdrRef.i_cksum));
    printf("Unique identifier: %d\n", ntohs(icmpHdrRef.i_id));
    printf("Sequence number: %d\n\n", ntohs(icmpHdrRef.i_seq));
 
};
 
//WSADATA            wsd;
 
RAW_SOCKET::RAW_SOCKET(int proto) //IPPROTO_ICMP
{
int                ret;    
 
/*
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
    {
        printf("WSAStartup() failed: %d\n", GetLastError());getchar();
        exit(-1);
    }
*/    
// Creating a raw socket with an undefined (raw) protocol
        
    s = WSASocket(AF_INET, SOCK_RAW, proto, NULL, 0,0);
    
    if (s == INVALID_SOCKET)
    {
        printf("WSASocket() failed: %d\n", WSAGetLastError());getchar();
        exit(-1);
    }
 
    // Enable the IP header include option 
    
    bOpt = TRUE; // If TRUE (while setting IP_HDRINCL), IP header is 
                 // submitted with data to be sent and 
                 // returned from data that is read.
    ret = setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *)&bOpt, sizeof(bOpt));
    if (ret == SOCKET_ERROR)
    {
        printf("setsockopt(IP_HDRINCL) failed: %d\n", WSAGetLastError());getchar();
        exit(-1);
    }
};
 
int RAW_SOCKET::BindSocket(u_long address)
{
    SOCKADDR_IN local;
    local.sin_family = AF_INET;
    //local.sin_port = htons((short)iPort); // for UDP or TCP
    local.sin_addr.s_addr = address;//htonl(INADDR_ANY);
    //local.sin_addr.s_addr = inet_addr(szInterface);
 
    if (bind(s, (SOCKADDR *)&local, sizeof(local)) == SOCKET_ERROR)
    {
        printf("bind() failed: %d\n", WSAGetLastError());getchar();
        return -1;
    }
    return 0;
};
 
///////////////////////////////////
pop3_main.cpp
///////////////////////////////////
 
//  POP3 TCP/IP почтовый сервер для одновременной работы с MAX_CONNECTIONS
//  клиентами
 
#include "server.h"
 
DWORD WINAPI ThreadFunc(SERVER_SOCKET* p_server_socket)
{
 
SERVER_SOCKET server; 
server = *p_server_socket; //через перегруженное присваивание (из-за строк)
 
server.report_file.open("pop3_report.txt",ios::app);
 
server.ReplyOnClientConnection();
 
int retval;
//*********************** Приём - передача сервера ***********************
while(true) {
 
if (!server.query) 
{
retval = server.recv_data();
if (retval==-1) break; 
// если сокетная ошибка, то:
}
 
retval = server.ProcessClientQuery();
// если критическая ошибка, то:
if (retval==-1) break; 
// Если сервер принял команду об окончании сеанса почтового соединения, то:
if (retval==1) 
{
server.report_file.close();
cout<<"The mail transaction successfully completed."<<endl;
return 1; 
}
 
// отправляем ответ клиенту, если это был запрос, а не данные
server.send_data();
 
} //end of while
//******************** Конец приёма - передачи сервера ******************* 
server.shutdown_and_closesocket();
 
return 0;
}
 
//////////////////////////////// main ////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/*
main() { 
 
DWORD dwThreadID_POP3;
 
if (CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFuncPOP3,
    0,0,&dwThreadID_POP3)==NULL) 
    cout<<GetLastError()<<endl;
 
getchar();
 
return 0;
}
*/
 
DWORD WINAPI ThreadFuncPOP3(void)
{
//cout<<"           The POP3 - server program."<<endl;
 
//cout<<endl<<"Type \"help\" to get help on commands."<<endl<<endl;
 
CONF conf;
conf.Init();
//conf.ProcessConfigCommands();
 
DISPATCH_SERVER_SOCKET s(conf);
 
s.accept_connect();
 
return 0;
}
 
///////////////////////////// end of main ////////////////////////////////
 
///////////////////////////////////
pop3_module.cpp
///////////////////////////////////
 
// Модуль, где находится вся POP3-реализация этого почтового сервера
 
#include "server.h"
 
//////////////////////////////////////////////////////////////////////////
 
int SERVER_SOCKET::ReplyOnClientConnection(void)
{
// отвечаем клиенту на его подключение (не на запрос клиента!)
set_buffer("+OK POP3 ");
strcat(Buffer,conf.Domain);
strcat(Buffer," is ready\r\n");
send_data();
return 0;
}
 
//////////////////////////////////////////////////////////////////////////
////////////////////////// Обработчик команд /////////////////////////////
 
int SERVER_SOCKET::ProcessClientQuery(void)
{
// Уже имеем в буфере запрос клиента и обрабатываем его
not_this_command=0;
 
///////////////////////// Команда "USER" /////////////////////////////////
 
if (!strncmp(Buffer,"USER ",5)&&mode.IsAuthorizationMode())
{
substring(Buffer,' ','\r', user.name);
 
if(conf.IsUserExistent(user.name)) // если пользователь существует, то
{
if(!user.lock) // если почтовый ящик не заперт, то
{
set_buffer("+OK User ");
strcat(Buffer,user.name);
strcat(Buffer," exists\r\n");
}
else
{
set_buffer("-ERR sorry, the mailbox for ");
strcat(Buffer,user.name);
strcat(Buffer," is currently locked\r\n");
}
}
else // если пользователь не существует
{
set_buffer("-ERR sorry, no mailbox for ");
strcat(Buffer,user.name);
strcat(Buffer," exists\r\n");
}
} else not_this_command++;
 
///////////////////////// Команда "PASS" /////////////////////////////////
 
if (!strncmp(Buffer,"PASS ",5)&&mode.IsAuthorizationMode())
{
char arg1[ADDRESS_MAX_LENGTH]={0},buf[20]={0};
substring(Buffer,' ','\r', arg1);
conf.GetPassword(user.name,user.password);
 
if (!strcmp(arg1,user.password)) // проверяем пароль
{
conf.ParseMailDrop(user.name);  // просматриваем почтовый ящик и 
// результаты этого просмотра (количество писем, имена их файлов, 
// размеры этих файлов и их общий размер) сохраняем в полях класса
 
set_buffer("+OK User ");
strcat(Buffer,user.name);
strcat(Buffer,"'s maildrop has ");
strcat(Buffer,itoa(conf.f_index,buf,10));
strcat(Buffer," message(s) (");
strcat(Buffer,itoa(conf.total_size,buf,10));
strcat(Buffer," octets)\r\n");
mode.SetTransactionMode();
user.lock=true; // запираем почтовый ящик
}
else set_buffer("-ERR invalid password\r\n");
} else not_this_command++;
 
///////////////////////// Команда "STAT" /////////////////////////////////
 
if (!strncmp(Buffer,"STAT",4)&&mode.IsTransactionMode())
{
char buf[20]={0};
 
set_buffer("+OK ");
strcat(Buffer,itoa(conf.f_index,buf,10));
strcat(Buffer," ");
strcat(Buffer,itoa(conf.total_size,buf,10));
strcat(Buffer,"\r\n");
conf.highest_number_accessed=1;
} else not_this_command++;
 
 
///////////////////////// Команда "LIST" /////////////////////////////////
 
if (conf.c_mes>conf.f_index) // заканчиваем передачу списка писем
{
set_buffer(".\r\n");
query = 0;
conf.c_mes = 0;
not_this_command--;
}
 
 
if (conf.c_mes>0&&conf.c_mes<=conf.f_index) // выдаём очередную запись
// о письме вида "<номер письма> <размер файла-письма>"
{
char buf[20]={0};
 
set_buffer(itoa(conf.c_mes,buf,10));
strcat(Buffer," ");
strcat(Buffer,itoa(conf.file[conf.c_mes-1].filesize,buf,10));
strcat(Buffer,"\r\n");
conf.c_mes++;
not_this_command--;
}
 
if (!strncmp(Buffer,"LIST",4)&&mode.IsTransactionMode())
{
char buf[ADDRESS_MAX_LENGTH]={0},arg2[ADDRESS_MAX_LENGTH]={0};
if(Buffer[4]!=' ') // если команда без аргументов, то:
{
set_buffer("+OK ");
strcat(Buffer,itoa(conf.f_index,buf,10));
strcat(Buffer," message(s) (");
strcat(Buffer,itoa(conf.total_size,buf,10));
strcat(Buffer," octets)\r\n");
query = 1;
conf.c_mes = 1;
}
else // если с аргументами, то:
{
substring(Buffer,' ','\r', arg2);
if(atoi(arg2)<=conf.f_index) // если номер сообщения корректный, то:
{
set_buffer("+OK ");
strcat(Buffer,arg2);
strcat(Buffer,itoa(conf.file[atoi(arg2)-1].filesize,buf,10));
strcat(Buffer,"\r\n");
}
else // если некорректный, то:
{
set_buffer("-ERR no such message, only ");
strcat(Buffer,itoa(conf.f_index,buf,10));
strcat(Buffer," messages in maildrop\r\n");
}
} // end else if(Buffer[4]!=' ')
} else not_this_command++;
 
 
///////////////////////// Команда "RETR" /////////////////////////////////
 
if (query==2) // если включён режим передачи сообщения,то
{ 
erase_buffer();
if(!mes_file.eof()) // пока не конец файла - сообщения
{
mes_file.getline(Buffer,sizeof(Buffer),10); // читаем очередную строку 
                                            // письма
strcat(Buffer,"\n"); // помещаем прочитанную строку в буфер для отправки
}
else // если достигнут конец файла
{
set_buffer("\r\n.\r\n");// то помещаем признак конца передачи
                        // данных в буфер для отправки
query=0; // снова разрешаем приём запросов
mes_file.close(); // закрвываем файл сообщения
} 
not_this_command--;
}
 
 
if (!strncmp(Buffer,"RETR",4)&&mode.IsTransactionMode())
{
char arg2[ADDRESS_MAX_LENGTH]={0},buf[ADDRESS_MAX_LENGTH]={0};
substring(Buffer,' ','\r', arg2);
 
if(atoi(arg2)<=conf.f_index) // если номер сообщения корректный, то:
{
set_buffer("+OK ");
strcat(Buffer,itoa(conf.file[atoi(arg2)-1].filesize,buf,10));
strcat(Buffer," octets\r\n");
query=2; // чтобы не попало на обработчик query==1
mes_file.open(conf.file[atoi(arg2)-1].filename,ios::in);
if(conf.highest_number_accessed<atoi(arg2))
conf.highest_number_accessed=atoi(arg2);
}
else // если некорректный, то:
{
set_buffer("-ERR no such message, only ");
strcat(Buffer,itoa(conf.f_index,buf,10));
strcat(Buffer," messages in maildrop\r\n");
}
} else not_this_command++;
 
///////////////////////// Команда "DELE" /////////////////////////////////
 
if (!strncmp(Buffer,"DELE",4)&&mode.IsTransactionMode())
{
char arg2[ADDRESS_MAX_LENGTH]={0},buf[ADDRESS_MAX_LENGTH]={0};
substring(Buffer,' ','\r', arg2);
 
if(atoi(arg2)<=conf.f_index) // если номер сообщения корректный, то:
{
conf.file[atoi(arg2)-1].del=true; // выставляем признак удаления 
                                 // файла-письма с данным номером
set_buffer("+OK message ");
strcat(Buffer,arg2);
strcat(Buffer," deleted\r\n");
if(conf.highest_number_accessed<atoi(arg2))
conf.highest_number_accessed=atoi(arg2);
}
else  // если некорректный, то:
{
set_buffer("-ERR no such message, only ");
strcat(Buffer,itoa(conf.f_index,buf,10));
strcat(Buffer," messages in maildrop\r\n");
}
} else not_this_command++;
 
///////////////////////// Команда "QUIT" /////////////////////////////////
 
if (!strncmp(Buffer,"QUIT",4))//&&!mode.IsTransactionMode())
{
if(mode.IsTransactionMode())
{
mode.SetUpdateMode();
 
for(int i=0;i<conf.f_index;i++) // удаляем все файлы-письма, у которых 
                                // выставлен признак удаления 
{
if(conf.file[i].del)
if(remove(conf.file[i].filename)==-1) // удаляем 
// отправленный e-mail
{cout<<"Could not delete sent e-mail"<<endl;getch();}
}
set_buffer("+OK POP3-server signing off (maildrop empty)\r\n");
user.lock=false; // отпираем почтовый ящик
}
 
else //if(mode.IsTransactionMode())
set_buffer("+OK terminating connection\r\n");
quit=1;
query=3; // чтобы не попало на обработчик query==2
} else not_this_command++;
 
///////////////////////// Команда "NOOP" /////////////////////////////////
 
if (!strncmp(Buffer,"NOOP",4)&&mode.IsTransactionMode())
{
set_buffer("+OK\r\n");
} else not_this_command++;
 
///////////////////////// Команда "LAST" /////////////////////////////////
 
if (!strncmp(Buffer,"LAST",4)&&mode.IsTransactionMode())
{
char buf[ADDRESS_MAX_LENGTH]={0};
set_buffer("+OK ");
strcat(Buffer,itoa(conf.highest_number_accessed,buf,10));
strcat(Buffer,"\r\n");
} else not_this_command++;
 
///////////////////////// Команда "RSET" /////////////////////////////////
 
if (!strncmp(Buffer,"RSET",4)&&mode.IsTransactionMode())
{
set_buffer("+OK\r\n");
for(int i=0;i<conf.f_index;i++) conf.file[i].del=false;
conf.highest_number_accessed=1;
} else not_this_command++;
 
 
if (quit==2) return 1; // прекращаем соединение
if (quit==1) quit++; // даём возможность отправить сообщение о прекращении
                     // соединения
 
if(not_this_command==10) set_buffer("-ERR invalid command\r\n");
 
return 0;
}
 
//////////////////////////////////////////////////////////////////////////
 
int CONF::ParseMailDrop(char* user) // название функции навеяно RFC 1225.
// функция просматривает почтовый ящик, идентифицирует отдельные 
// файлы-письма, определяет размер каждого и общий их размер
{
 
WIN32_FIND_DATA file_info;
HANDLE file_handle;
char filename[MAX_PATH]={0};
char parent_path[MAX_PATH]={0};
 
ZeroMemory(file,sizeof(file));
f_index=0;
strcpy(filename,Path);
strcat(filename,"\\");
strcat(filename,user);
strcpy(parent_path,filename);
strcat(parent_path,"\\"); 
strcat(filename,"\\*"); // текущая директория
 
file_handle = FindFirstFile((LPSTR)filename,&file_info);
if (file_handle==INVALID_HANDLE_VALUE) 
    {cout<<"FindFirstFile failed with error: "<<GetLastError()<<endl;
    return -1;}
 
while(FindNextFile(file_handle,&file_info))
if(
   file_info.dwFileAttributes!=FILE_ATTRIBUTE_DIRECTORY&&
   strncmp(file_info.cFileName,"password",8) 
   && strncmp(file_info.cFileName,"..",2) /* этого компонента условия 
(т.е. strncmp(file_info.cFileName,"..",2) )поначалу здесь не было. 
Дома у меня и без него всё работало, а когда я принёс 
сдавать, то именно из-за отсутствия этой строки программа не
работала. Ради интереса попробуйте закомментировать эту строку
и запустить в таком виде программу в ДГТУ в а.358.
*/
   ) 
{
file[f_index].filesize=(int)((file_info.nFileSizeHigh * MAXDWORD) 
                       + file_info.nFileSizeLow);
 
strcpy(file[f_index].filename,parent_path);
strcat(file[f_index++].filename,file_info.cFileName);
}
 
FindClose(file_handle);cout<<endl;
 
total_size=0;
for (int i=0;i<f_index;i++)
total_size+=file[i].filesize;
 
return f_index;
}
 
//////////////////////////////////////////////////////////////////////////
 
MODE::MODE(void)// режим соединения (для нормальной работы с Outlook Express
// этот класс не нужен, я его сделал ,чтобы быть ближе к RFC 1225)
{
authorization_mode=true;
transaction_mode=false;
update_mode=false;
}
 
void MODE::SetAuthorizationMode(void)
{
authorization_mode=true;
transaction_mode=false;
update_mode=false;
}
void MODE::SetTransactionMode(void)
{
authorization_mode=false;
transaction_mode=true;
update_mode=false;
}
void MODE::SetUpdateMode(void)
{
authorization_mode=false;
transaction_mode=false;
update_mode=true;
}
 
bool MODE::IsAuthorizationMode(void){return authorization_mode;}
bool MODE::IsTransactionMode(void){return transaction_mode;}
bool MODE::IsUpdateMode(void){return update_mode;}
 
//////////////////////////////////////////////////////////////////////////
Клиент(raw_send):
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//////////////////////////////
RAW_SEND.CPP
//////////////////////////////
 
#include "packet.h"
 
// Global variables
 
u_long         dwToIP,               // IP to send to
               dwFromIP;             // IP to send from (spoof)
u_short        iToPort,              // Port to send to
               iFromPort;            // Port to send from (spoof)
DWORD          dwCount;              // Number of times to send
char           strMessage[MAX_MESSAGE]; // Message to send
 
 
void ICMP_PACKET::FillFields(PARAM* param)
{
    
u_short               // Lots of sizes needed to fill
                       //iUdpSize,     // the various headers with
                       iIPVersion,
                       iIPSize,
                       cksum = 0;
 
dwToIP = inet_addr(param[6].name);
dwFromIP = inet_addr(param[5].name); 
 
ptr=NULL;
ZeroMemory(buf,MAX_PACKET);
 
//iTotalSize = sizeof(ipHdr) + sizeof(icmpHdr) + strlen(strMessage);
    
    iTotalSize = sizeof(ipHdr) + sizeof(icmpHdr);
 
    iIPVersion = 4;
    iIPSize = sizeof(ipHdr) / sizeof(u_long);
    //
    // IP version goes in the high order 4 bits of ip_verlen. The
    // IP header length (in 32-bit words) goes in the lower 4 bits.
    //
    ipHdr.ip_verlen = (iIPVersion << 4) | iIPSize;
    ipHdr.ip_tos = atoi(param[2].name);  //0  // IP type of service
    ipHdr.ip_totallength = htons(iTotalSize); // Total packet len
    ipHdr.ip_id = 0;                 // Unique identifier: set to 0
    ipHdr.ip_offset = htons(atoi(param[3].name)); //0; // Fragment offset field
    ipHdr.ip_ttl = atoi(param[4].name); //128;  // Time to live
    ipHdr.ip_protocol = 0x01;        // Protocol(ICMP) 
    ipHdr.ip_checksum = 0 ;          // IP checksum
    ipHdr.ip_srcaddr = dwFromIP;     // Source address
    ipHdr.ip_destaddr = dwToIP;      // Destination address
    //
    // Initalize the UDP header
    //
    //iUdpSize = sizeof(udpHdr) + strlen(strMessage);
    /*
    iUdpSize = sizeof(udpHdr);
 
    udpHdr.src_portno = htons(iFromPort) ;
    udpHdr.dst_portno = htons(iToPort) ;
    udpHdr.udp_length = htons(iUdpSize) ;
    udpHdr.udp_checksum = 0 ;*/
 
    // Initalize the ICMP header
 
    icmpHdr.i_type = (u_char)atoi(param[7].name); //0; //put here a number in the range 0-127 (except for
    //the error numbers) 
    icmpHdr.i_code = (u_char)atoi(param[8].name); /* 0; put here a number in the range 0-127, 
    This way you can build your own ICMP-message types 
    for hundreds of different occasions.*/
    icmpHdr.i_cksum = 0;
    icmpHdr.i_id = htons(atoi(param[9].name)); //0;
    icmpHdr.i_seq = htons(atoi(param[10].name)); //0;
    icmpHdr.i_cksum = checksum((u_short*)&icmpHdr, sizeof(icmpHdr));
 
    
    // Now assemble the IP and UDP headers along with the data
    //  so we can send it
            
    ZeroMemory(buf, MAX_PACKET);
    ptr = buf;
 
    memcpy(ptr, &ipHdr, sizeof(ipHdr));   ptr += sizeof(ipHdr);
    //memcpy(ptr, &udpHdr, sizeof(udpHdr)); ptr += sizeof(udpHdr);
    memcpy(ptr, &icmpHdr, sizeof(icmpHdr)); ptr += sizeof(icmpHdr);
    //memcpy(ptr, strMessage, strlen(strMessage));
 
    // Apparently, this SOCKADDR_IN structure makes no difference.
    // Whatever we put as the destination IP addr in the IP header
    // is what goes. Specifying a different destination in remote
    // will be ignored.
    //
    remote.sin_family = AF_INET;
    //remote.sin_port = htons(iToPort);
    remote.sin_addr.s_addr = dwToIP;
 
    //PrintPacket();
};
 
 
int RAW_SOCKET::SendPackets(char* buf, u_short iTotalSize, 
                            struct sockaddr_in *p_remote, DWORD dwCount)
{
    DWORD              i,j;
    int                ret;
 
    ((ICMP_PACKET*)buf)->PrintPacket();
 
    for(i = 0; i < dwCount; i++)
    {
    ret = sendto(s, buf, iTotalSize, 0, (SOCKADDR *)p_remote, 
            sizeof(struct sockaddr_in));
 
        if (ret == SOCKET_ERROR)
        {
            printf("sendto() failed: %d\n", WSAGetLastError());getchar();
            break;
        }
        else
        {
            buf[ret] = '\0';
            printf("Info sent to [%s]:\n", 
                inet_ntoa(p_remote->sin_addr));
            
            for (j=0;j<(u_int)ret;j++) printf("%d", buf[j]);
            printf("%c",'\n');
            for (j=0;j<(u_int)ret;j++) printf("%c", buf[j]);
            printf("\nNumber of bytes sent: %d\n", ret);
        }
    } // end for
 
    return 0;
};
 
// Function: send_icmp_sequence
//
// Description:
//    Create the raw socket and set the IP_HDRINCL option.
//    Following this, assemble the IP and ICMP packet headers by
//    assigning the correct values and calculating the checksums.
//    Then fill in the data and send to its destination.
//
int send_icmp_sequence(PARAM* param)
{
    ICMP_PACKET        packet; 
    RAW_SOCKET         raw_socket(IPPROTO_RAW);
 
    //dwCount = DEFAULT_COUNT;
    dwCount = atoi(param[1].name);
    
    packet.FillFields(param);
 
    raw_socket.SendPackets(packet.buf, packet.iTotalSize, 
        &packet.remote, dwCount);
 
    closesocket(raw_socket.s) ;
    
//  WSACleanup() ;
 
    getchar();
    return 0;
}
 
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
 
// Function: checksum
//
// Description:
//    This function calculates the 16-bit one's complement sum
//    for the supplied buffer. 
//    This function is taken from a MSDN v6.0 example (PING app example)
//
u_short checksum(u_short *buffer, int size)
{
    u_long cksum=0;
 
    while (size > 1)
    {
        cksum += *buffer++;
        size  -= sizeof(u_short);   
    }
    if (size)
    {
        cksum += *(u_char*)buffer;   
    }
    cksum = (cksum >> 16) + (cksum & 0xffff);
    cksum += (cksum >>16); 
 
    return (u_short)(~cksum); 
}
 
//////////////////////////////
packet.CPP
//////////////////////////////
 
#include "packet.h"
 
void ICMP_PACKET::PrintPacket(void)
{
    IP_HDR             ipHdrRef;
    ICMP_HDR           icmpHdrRef;
    struct in_addr     addrRef;
 
    printf("Prepared to send: %d bytes\n", iTotalSize);
    
    ZeroMemory(&ipHdrRef,sizeof(ipHdrRef));
    ZeroMemory(&icmpHdrRef,sizeof(icmpHdrRef));
    ZeroMemory(&addrRef,sizeof(addrRef));
 
    memcpy(&ipHdrRef, buf, sizeof(ipHdrRef)); 
    memcpy(&icmpHdrRef, (buf + sizeof(ipHdrRef)), sizeof(icmpHdrRef));
 
 
    printf("The IP-header content:\n\n");
 
    printf("Type of service: %d\n", ipHdrRef.ip_tos);
    printf("Total packet length: %d\n", ntohs(ipHdrRef.ip_totallength));
    printf("Unique identifier: %d\n", ntohs(ipHdrRef.ip_id));
    printf("Fragment offset field: %d\n", ntohs(ipHdrRef.ip_offset));
    printf("Time to live: %d\n", ipHdrRef.ip_ttl);
    printf("Encapsulated protocol number: %d\n", ipHdrRef.ip_protocol);
    printf("Checksum: %d\n", ntohs(ipHdrRef.ip_checksum));
    addrRef.S_un.S_addr = ipHdrRef.ip_srcaddr;
    printf("Source address: %s\n", inet_ntoa(addrRef));
    ZeroMemory(&addrRef,sizeof(addrRef));
    addrRef.S_un.S_addr = ipHdrRef.ip_destaddr;
    printf("Destination address: %s\n\n", inet_ntoa(addrRef));
    
    printf("The ICMP-header content:\n\n");
    
    printf("Type: %d\n", icmpHdrRef.i_type);
    printf("Code: %d\n", icmpHdrRef.i_code);
    printf("Checksum: %d\n", ntohs(icmpHdrRef.i_cksum));
    printf("Unique identifier: %d\n", ntohs(icmpHdrRef.i_id));
    printf("Sequence number: %d\n\n", ntohs(icmpHdrRef.i_seq));
 
};
 
//WSADATA            wsd;
 
RAW_SOCKET::RAW_SOCKET(int proto) //IPPROTO_ICMP
{
int                ret;    
 
/*
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
    {
        printf("WSAStartup() failed: %d\n", GetLastError());getchar();
        exit(-1);
    }
*/    
// Creating a raw socket with an undefined (raw) protocol
        
    s = WSASocket(AF_INET, SOCK_RAW, proto, NULL, 0,0);
    
    if (s == INVALID_SOCKET)
    {
        printf("WSASocket() failed: %d\n", WSAGetLastError());getchar();
        exit(-1);
    }
 
    // Enable the IP header include option 
    
    bOpt = TRUE; // If TRUE (while setting IP_HDRINCL), IP header is 
                 // submitted with data to be sent and 
                 // returned from data that is read.
    ret = setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *)&bOpt, sizeof(bOpt));
    if (ret == SOCKET_ERROR)
    {
        printf("setsockopt(IP_HDRINCL) failed: %d\n", WSAGetLastError());getchar();
        exit(-1);
    }
 
};
 
int RAW_SOCKET::BindSocket(u_long address)
{
    SOCKADDR_IN local;
    local.sin_family = AF_INET;
    //local.sin_port = htons((short)iPort); // for UDP or TCP
    local.sin_addr.s_addr = address;//htonl(INADDR_ANY);
    //local.sin_addr.s_addr = inet_addr(szInterface);
 
    if (bind(s, (SOCKADDR *)&local, sizeof(local)) == SOCKET_ERROR)
    {
        printf("bind() failed: %d\n", WSAGetLastError());getchar();
        return -1;
    }
    return 0;
};
 
//////////////////////////////
http_plugin.CPP
//////////////////////////////
 
// Модуль, где находится HTTP-плагин
 
#include <fstream.h>
#include <winsock2.h>
#include <time.h>
#include <conio.h>
 
#include "packet.h"
 
#define MAX_CONNECTIONS 5
#define SIZE_OF_BUFFER 8192 
 
#define ADDRESS_MAX_LENGTH 64
 
char* getspos(char* search_string,char search_symbol);
// получить указатель на первое вхождение символа в строке
char* substring(char* st,char s1,char s2,char* ret);
// извлечь в ret подстроку из st, заключённую между символами s1 и s2
// (не включая s1 и s2 в возвращаемое значение)
void readcomment(fstream& file); // считать и выбросить комментарий 
// из файла "conf.inf"
 
 
 
//////////////////////////////////////////////////////////////////////////
 
class CONF_HTTP
{ // здесь содержится вся конфигурация HTTP-сервера
public:
fstream conf_file; // из этого файла при запуске программы считываем 
// настройки HTTP-сервера
char ip_address[32]; // ip-адрес этого сервера
int port; //порт, на который будем принимать HTTP-запросы (обычно 80)
int echo; // выводить ли на экран каждое действие
 
CONF_HTTP(void);
void ProcessConfigCommands(void);
void Init(void);
};
 
//////////////////////////////////////////////////////////////////////////
 
class DISPATCH_SERVER_SOCKET_HTTP
{
public:
long connection_time;
struct sockaddr_in server_address,client_address;
int retval,size_of_client_address;
WSADATA wsaData;
SOCKET dispatch_server_socket, msg_server_socket;
DWORD dwThreadID;
DISPATCH_SERVER_SOCKET_HTTP(CONF_HTTP& conf);
CONF_HTTP conf;
int accept_connect(void);
};
 
//////////////////////////////////////////////////////////////////////////
 
class SERVER // сложный класс, включающий в себя HTTP-сокет
{
public:
char Buffer[SIZE_OF_BUFFER];
SOCKET msg_server_socket;
 
int quit; // флаг, который показывает, что сеанс связи окончен
int block_reply;
PARAM param[100];
int param_index;
 
CONF_HTTP conf;
long connection_time;
fstream report_file; // в этот файл запишем всё, что сервер получает 
// и отправляет
 
SERVER(void);
int recv_data(void);
int send_data(void);
int shutdown_and_closesocket(void);
void erase_buffer(void);
void set_buffer(char*);
 
int ProcessClientQuery(void);
int ProcessControlString(char* c_string);
 
void CreateQueryForm(char* temp_path); // считать в буфер с диска htm-файл (форму запроса) для отправки клиенту
int ProcessHTTPCommand(void);
 
SERVER& operator=(SERVER& right);
};
 
//////////////////////////////////////////////////////////////////////////
 
DWORD WINAPI ThreadFuncHTTP(SERVER* p_server);
 
//////////////////////////////////////////////////////////////////////////
 
DISPATCH_SERVER_SOCKET_HTTP::DISPATCH_SERVER_SOCKET_HTTP(CONF_HTTP& conf_ref)
{
// Инициализируем библиотеку WS2_32.DLL
if ((retval = WSAStartup(0x202,&wsaData)) != 0) 
    {cerr<<"WSAStartup failed with error "<<retval<<endl;
    getch();WSACleanup();exit(-1);}
 
size_of_client_address = sizeof(client_address);
 
// Создаём базовый(диспетчерский) сокет сервера, настроенный на TCP
dispatch_server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 
if (dispatch_server_socket == INVALID_SOCKET)
    {cerr<<"socket() failed with error "<<WSAGetLastError()<<endl;
getch();WSACleanup();exit(-1);} 
 
// Записываем в адресную структуру IP адрес сервера и порт сервера
server_address.sin_family = AF_INET;
server_address.sin_port = htons(conf_ref.port);//Port MUST be in Network Byte Order
server_address.sin_addr.S_un.S_addr = inet_addr (conf_ref.ip_address);
 
// Связываем адрес сервера с базовым(диспетчерским) сокетом сервера
if (bind(dispatch_server_socket,(SOCKADDR*) &server_address, 
         sizeof(server_address))==SOCKET_ERROR)
    {cerr<<"bind() failed with error "<<WSAGetLastError()<<endl;
    getch();WSACleanup();exit(-1);}
 
// Переводим базовый(диспетчерский) сокет сервера на режим 
// прослушивание/диспетчеризация сигналов на подключение и устанавливаем 
// размер очереди одновременных обращений к серверу
if (listen(dispatch_server_socket,MAX_CONNECTIONS)==SOCKET_ERROR)
    {cerr<<"listen() failed with error "<<WSAGetLastError()<<endl;
    getch();WSACleanup();exit(-1);}
 
conf=conf_ref;
}
 
//////////////////////////////////////////////////////////////////////////
 
int DISPATCH_SERVER_SOCKET_HTTP::accept_connect(void)
{
//cout<<"Waiting for a client's connection..."<<endl<<endl;
 
//************************************************************************
while (true)
{
// Ждём очередное подключение к серверу (функцией connect()) клиента и, 
// дождавшись, возвращаем виртуальный сокет сервера - для двухстороннего 
// обмена сообщениями с данным клиентом
    msg_server_socket = accept(dispatch_server_socket,
                    (SOCKADDR*) &client_address, &size_of_client_address); 
 
// Если случилась ошибка ожидания клиента (кроме отсутствия вызова клиента), то:
if (msg_server_socket==INVALID_SOCKET)
    {cerr<<"accept() failed with error "<<WSAGetLastError()<<endl;
    // Закрываем базовый(диспетчерский) сокет сервера
    if (closesocket(dispatch_server_socket)==SOCKET_ERROR)
    cerr<<"closesocket() failed with error "<<WSAGetLastError()<<endl;
    WSACleanup();return 0;}
 
// Выводим на экран время подключения клиента, его IP-адрес и порт
if ( client_address.sin_family == AF_INET) // если это TCP-клиент,то:
{
    connection_time=time(0);
    cout<<"Accepted HTTP-connection on: "<<ctime(&connection_time)
    <<"from IP address: "<<inet_ntoa(client_address.sin_addr)<<" port: "
    <<ntohs(client_address.sin_port)<<endl<<endl;
}
 
// Для каждого подключившегося клиента создаём нить и передаём в неё
// адрес виртуального сокета сервера для двухстороннего 
// обмена сообщениями с данным клиентом (нити нужны здесь для того, чтобы
// позволить серверу работать одновременно с несколькими клиентами)
SERVER server;
server.msg_server_socket = msg_server_socket;
server.connection_time = connection_time;
server.conf=conf;
 
if (CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFuncHTTP,
    (LPVOID)&server,0,&dwThreadID)==NULL) 
    cout<<GetLastError()<<endl;
}// end of while
//************************************************************************
 
// Закрываем базовый(диспетчерский) сокет сервера
    if (closesocket(dispatch_server_socket)==SOCKET_ERROR)
    cerr<<"closesocket() failed with error "<<WSAGetLastError()<<endl;
 
// Освобождаем ресурсы с помощью библиотеки WS2_32.DLL
WSACleanup();
return 0;
};
 
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
 
SERVER::SERVER(void)
{
erase_buffer();
quit = 0;// Нужно ли закончить сеанс связи
connection_time = 0;
block_reply = 1;
ZeroMemory(param,sizeof(param));
param_index=0;
};
 
//////////////////////////////////////////////////////////////////////////
 
int SERVER::shutdown_and_closesocket(void)
{
cout<<"Terminating HTTP-connection."<<endl<<endl;
 
// Блокируем получение - отправку сообщений у виртуального сокета сервера
if (shutdown(msg_server_socket,SD_BOTH)==SOCKET_ERROR) 
{cerr<<"shutdown() failed with error "<<WSAGetLastError()<<endl;return -1;}
 
// Закрываем виртуальный сокет сервера, связанный с данным клиентом
if (closesocket(msg_server_socket)==SOCKET_ERROR) 
{cerr<<"closesocket() failed with error "<<WSAGetLastError()<<endl;
return -1;}
return 0;
};
 
//////////////////////////////////////////////////////////////////////////
 
void SERVER::erase_buffer(void)
{
ZeroMemory(&Buffer,sizeof(Buffer));
}
 
//////////////////////////////////////////////////////////////////////////
 
void SERVER::set_buffer(char* string)
{
erase_buffer();
strcpy(Buffer,string);
}
 
//////////////////////////////////////////////////////////////////////////
 
int SERVER::recv_data(void)
{
erase_buffer();
 
// Ждём приёма сообщения от клиента
char ch;
int retval;
char S[]={"S: "};
 
for (int i=0; i<sizeof(Buffer); i++)
{
// Принимаем побайтно то, что клиент отправил как цельное сообщение
// (для того, чтобы мы могли распознавать отдельные команды)
retval = recv(msg_server_socket,&ch,sizeof(char),0 );
if (retval == SOCKET_ERROR) 
    {cerr<<"recv() failed: error "<<WSAGetLastError()<<endl;
    closesocket(msg_server_socket); return -1;}
 
else {Buffer[i]=ch; if (ch =='\n') break;};
};      
if(conf.echo)
cout<<"S:  "<<Buffer<<endl;
 
report_file.write(S,strlen(S));
report_file.write(Buffer,strlen(Buffer));
 
return 0;
};
 
//////////////////////////////////////////////////////////////////////////
 
int SERVER::send_data(void)
{
int retval;
char R[]={"R: "};
 
retval = send(msg_server_socket,Buffer,strlen(Buffer),0);// ни в коем 
                                          // случае не sizeof(Buffer)!
if (retval == SOCKET_ERROR) 
    {cerr<<"send() failed: error "<<WSAGetLastError()<<endl;return -1;}
 
if(conf.echo)
cout<<"R:  "<<Buffer<<endl;
 
report_file.write(R,strlen(R));
report_file.write(Buffer,strlen(Buffer));
erase_buffer();
return 0;
};
 
//////////////////////////////////////////////////////////////////////////
 
SERVER& SERVER::operator=(SERVER& right)
{
if (&right!=this)
{
msg_server_socket = right.msg_server_socket;
connection_time = right.connection_time;
conf=right.conf;
}
return *this;
}
 
///////////////// Описание конфигурационного объекта /////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
 
void CONF_HTTP::Init(void)
{
fstream empty_file;
 
conf_file.open("http_conf.inf",ios::in);
 
conf_file>>ip_address; 
readcomment(conf_file);
conf_file>>port;
readcomment(conf_file);
conf_file>>echo;
readcomment(conf_file);
 
conf_file.close();
 
empty_file.open("http_report.txt",ios::trunc);
empty_file.close();
 
};
 
//////////////////////////////////////////////////////////////////////////
 
CONF_HTTP::CONF_HTTP(void)
{
ZeroMemory(ip_address,sizeof(ip_address));
port=0;
echo=false;
};
 
//////////////////////////////////////////////////////////////////////////
 
 
int SERVER::ProcessClientQuery(void)
{
 
if (!strncmp(Buffer,"GET /?",6))
{
char arg[MAX_PATH*10]={0};
substring(Buffer,'?','%',arg);
ProcessControlString(arg);
}
 
if (!strncmp(Buffer,"\r\n",2))
{
set_buffer("HTTP/1.1 200 OK\r\n");
fstream file;
char ch;
 
char temp_path[MAX_PATH]={0};
 
CreateQueryForm(temp_path); // Здесь решаем вопрос об отправке клиенту 
                            // формы на основании его запроса
 
size_t i=strlen(Buffer);
file.open(temp_path,ios::in);
 
while(!file.eof())
{
file.read(&ch,1);
Buffer[i++]=ch;
}
 
quit=1;block_reply=0; 
}
return 0;
}
 
//////////////////////////////////////////////////////////////////////////
 
int SERVER::ProcessControlString(char* st)
{
//T01=ddddddddddddd&T02=ggggggggggggg&
size_t i;
int j=0;
int flag=0;
for(i=0;i<strlen(st);i++) // разбиваем строку на подстроки
{
if(st[i]=='&') {flag=0;param_index++;j=0;}
if(flag==1) param[param_index].name[j++]=st[i];
if(st[i]=='=') flag=1;
}
 
return 0;
}
 
//////////////////////////////////////////////////////////////////////////
//  HTTP TCP/IP почтовый сервер для одновременной работы с MAX_CONNECTIONS
//  клиентами
 
int echo_gl;
 
DWORD WINAPI ThreadFuncHTTP(SERVER* p_server)
{
 
SERVER server; 
server = *p_server; //через перегруженное присваивание (из-за строк)
 
server.report_file.open("http_report.txt",ios::app);
 
int retval;
//*********************** Приём - передача сервера ***********************
while(true) {
 
retval = server.recv_data();
if (retval==-1) break;  // если сокетная ошибка
 
retval = server.ProcessClientQuery();
// если критическая ошибка, то:
if (retval==-1) break; 
// Если сервер принял команду об окончании сеанса соединения, то:
if (retval==1) 
{
server.report_file.close();
cout<<"The HTTP-transaction successfully completed."<<endl;
return 1; 
}
 
// отправляем ответ клиенту, если это был запрос, а не данные
if(!server.block_reply) server.send_data();
 
if(server.quit) break;
 
} //end of while
//******************** Конец приёма - передачи сервера ******************* 
server.shutdown_and_closesocket();
 
if(server.conf.echo)
for (int i=0;i<server.param_index;i++)
cout<<"Parametr #"<<i<<": "<<server.param[i].name<<endl;
 
server.ProcessHTTPCommand(); // Здесь на основе полученных от HTTP-клиента 
                             // параметров производим запланированные 
                             // действия
return 0;
}
 
//////////////////////////////// main ////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
 
int main(void)
{
 
CONF_HTTP conf;
conf.Init();
 
printf("The IP-packet generator.\n\nWaiting for HTTP-query...\n\n");
 
DISPATCH_SERVER_SOCKET_HTTP s(conf);
 
s.accept_connect();
 
return 0;
}
 
///////////////////////////// end of main ////////////////////////////////
//////////////////////////////////////////////////////////////////////////
 
//////////////////////////////////////////////////////////////////////////
 
char* substring(char* st,char s1,char s2,char* ret)
{
ZeroMemory(ret,sizeof(ret));
strncpy(ret,getspos(st,s1)+1,getspos(st,s2)-getspos(st,s1)-1);
return ret;
}
 
//////////////////////////////////////////////////////////////////////////
 
char* getspos(char* search_string,char search_symbol)
{
int count=0;
 
while(true)
{
if (count>200) 
{
cout<<"The search symbol "<<search_symbol<<"was not found."<<endl;
getch();return NULL;
}
if (*search_string != search_symbol) 
{search_string++; count++;} else break;
}// endwhile
 
return search_string;
}
 
//////////////////////////////////////////////////////////////////////////
 
void readcomment(fstream& file)
{
char empty[MAX_PATH]={0}; // буфер для считывания
ZeroMemory(empty,sizeof(empty));
file.getline(empty,sizeof(empty),10);
}
 
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
 
void SERVER::CreateQueryForm(char* temp_path)
{
 
// Здесь решаем вопрос об отправке клиенту формы на основании его 
// запроса
 
if(!strcmp(param[0].name,"send")) 
{
if(!strcmp(param[1].name,"V1")) 
strcpy(temp_path,"http_icmp_form.htm");
if(!strcmp(param[1].name,"V2")) 
strcpy(temp_path,"http_attack_form.htm");
}
 
else 
if(!strcmp(param[0].name,"icmp")) 
strcpy(temp_path,"http_icmp_reply.htm");
else 
if(!strcmp(param[0].name,"attack")) 
strcpy(temp_path,"http_attack_reply.htm");
 
};
 
//////////////////////////////////////////////////////////////////////////
 
int SERVER::ProcessHTTPCommand(void)
{
 
if(!strcmp(param[0].name,"icmp")||!strcmp(param[0].name,"attack")) 
{
 
send_icmp_sequence(param);
 
cout<<"It was done by the HTTP-client."<<endl;
}
 
return 0;
};
 
//////////////////////////////
packet.h
//////////////////////////////
 
#pragma pack(1)
 
#define WIN32_LEAN_AND_MEAN   // Windows Headers use this symbol 
// to exclude rarely-used header files. Please refer to Windows.H 
//to determine the files that will be excluded when this symbol is defined
 
#include <winsock2.h>
#include <ws2tcpip.h>
 
#include <stdio.h>
#include <stdlib.h>
 
#define MAX_MESSAGE        4068
#define MAX_PACKET         4096
#define ICMP_ECHO          8
#define MAX_ICMP_PACKET    1024      // Max ICMP packet size
 
//
// Setup some default values 
//
#define DEFAULT_PORT_SEND       //5001
//#define DEFAULT_PORT_RECV       5000
//#define DEFAULT_IP_SEND        "127.0.0.1"
//#define DEFAULT_IP_RECV        "127.0.0.1"
//#define DEFAULT_COUNT           1 //5
#define DEFAULT_MESSAGE    "This is a test"
//char  szInterface[32] = "10.0.0.1";  // Default interface to read datagrams from
 
//
// Define the IP header. Make the version and length field one
// character since we can't declare two 4 bit fields without
// the compiler aligning them on at least a 1 byte boundary.
//
typedef struct ip_hdr
{
    u_char  ip_verlen;        // IP version & length
    u_char  ip_tos;           // IP type of service
    u_short ip_totallength;   // Total length
    u_short ip_id;            // Unique identifier 
    u_short ip_offset;        // Fragment offset field
    u_char  ip_ttl;           // Time to live
    u_char  ip_protocol;      // Protocol(TCP,UDP etc)
    u_short ip_checksum;      // IP checksum
    u_int   ip_srcaddr;       // Source address
    u_int   ip_destaddr;      // Destination address
} IP_HDR, *PIP_HDR, FAR* LPIP_HDR;
//
// Define the UDP header 
//
typedef struct udp_hdr
{
    u_short src_portno;       // Source port number
    u_short dst_portno;       // Destination port number
    u_short udp_length;       // UDP packet length
    u_short udp_checksum;     // UDP checksum (optional)
} UDP_HDR, *PUDP_HDR;
 
typedef struct icmp_hdr 
{
    BYTE   i_type;
    BYTE   i_code;                 // Type sub code
    USHORT i_cksum;
    USHORT i_id;
    USHORT i_seq;
} ICMP_HDR, *PICMP_HDR;
 
u_short checksum(u_short *buffer, int size);
 
typedef struct tag_param{char name[100];} PARAM;
 
//////////////////////////////////////////////////////////////////////////
 
class ICMP_PACKET
{
public:
char    buf[MAX_PACKET],*ptr;
    
IP_HDR    ipHdr;
ICMP_HDR  icmpHdr;
u_short iTotalSize;
struct sockaddr_in remote;       // IP addressing structures
 
void PrintPacket(void);
void FillFields(PARAM* param);
};
 
class RAW_SOCKET
{
public:
SOCKET    s;
BOOL      bOpt;
RAW_SOCKET(int proto);
int SendPackets(char* buf, u_short TotalSize, 
            struct sockaddr_in *p_remote, DWORD amount);
int BindSocket(u_long address);
int RecvPackets(void);
};
 
int send_icmp_sequence(PARAM* param);
Добавлено через 24 минуты
получается это 2 сервера. а клиента нету. значит мне нужно написать клиент который бы подключался к ним...

Добавлено через 1 час 19 минут
написал клиент.
УРА конектится!
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
#include <vcl.h>
#pragma hdrstop
#include <winsock2.h>
#include <stdio.h>
#include <conio.h>
 
//---------------------------------------------------------------------------
 
#pragma argsused
 
int main(void)
{
    WORD v=MAKEWORD(2,0);
    WSADATA d;
    int e=WSAStartup(v,&d);
    if (e)
    {
        perror("error initializing winsock");
        return 1;
    }
    struct sockaddr_in peer;
    int s;
    int rc;
    char buf[1];
    peer.sin_family=AF_INET;
    peer.sin_port=htons(110);
    peer.sin_addr.s_addr=inet_addr("127.0.0.1");
    s=socket(AF_INET,SOCK_STREAM,0);
    if (s<0)
    {
        perror("error calling socket");
        return 1;
    }
    rc=connect(s,(struct sockaddr *)&peer,sizeof(peer));
    if (rc)
    {
        perror("error calling connect");
        return 1;
    }
    rc=send(s,"help",4,0);
    if (rc<=0)
    {
        perror("error calling send");
        return 1;
    }
 
    rc=recv(s,buf,1,0);
    if (recv<=0)
        perror("error calling recv");
    else
        printf("%c\n",buf[0]);
    if (closesocket(s))
        perror("error calling closesocket");
    WSACleanup();
    getch();
    return 0;
}
теперь нужно разобраться с передачей данных.
что мне щас нужно: получать от сервера или посылать... и что имено посылать или принимать

Добавлено через 16 часов 24 минуты
кароче пока что вот такой клиентик...
проблема - сообщения не отправляются в цикле, т.е. в клиенте отправил, а на сервер ничего не приъодит, НО когда закрываю клиент, то все сообщения что писал приходят на сервак.
Как сделать что б отправлялись в цикле, а не после закрытия клиента?
Вообще мне просто нужен клиент в котором можно набирать команды и отправлять на сервер в любом количестве. всё.
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//---------------------------------------------------------------------------
 
#include <vcl.h>
#pragma hdrstop
 
//---------------------------------------------------------------------------
 
 
#pragma argsused
#include <stdio.h>
#include <conio.h>
#include <winsock2.h>
#include <iostream.h>
 
int main()
{
    WORD ver = MAKEWORD(2,2);
    WSADATA wsaData;
    int retVal=0;
 
    WSAStartup(ver,(LPWSADATA)&wsaData);
 
    LPHOSTENT hostEnt;
 
    hostEnt = gethostbyname("127.0.0.1");
 
    if(!hostEnt)
    {
        printf("Unable to collect gethostbyname\n");
        WSACleanup();
        return 1;
    }
 
    //Создаем сокет
    SOCKET clientSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
 
    if(clientSock == SOCKET_ERROR)
    {
        printf("Unable to create socket\n");
        WSACleanup();
        return 1;
    }
 
    SOCKADDR_IN serverInfo;
 
    serverInfo.sin_family = PF_INET;
    serverInfo.sin_addr = *((LPIN_ADDR)*hostEnt->h_addr_list);
    serverInfo.sin_port = htons(110);
 
    retVal=connect(clientSock,(LPSOCKADDR)&serverInfo, sizeof(serverInfo));
    if(retVal==SOCKET_ERROR)
    {
        printf("Unable to connect\n");
        WSACleanup();
        return 1;
    }
   
    char Message[200];
    int Menu;
    do {
        printf("1. Send message;\n");
        printf("2. Get Message;\n");
        printf("3. Quit;\n");
 
        printf("Make your selection: ");
        scanf("%i", &Menu);
 
        switch (Menu) {
        case 1:
            // Отправка сообщения серверу
            printf("Enter message: ");
            scanf("%199s", Message, 200);
            if (send(clientSock, Message, strlen(Message) + 1, 0) != SOCKET_ERROR) printf("Sent!\n");
            else printf("Error of sending!\n");
        break;
        case 2:
            // Приём сообщения от сервера
            if (recv(clientSock, Message, 200, 0) != SOCKET_ERROR) {
                printf("%s\n", Message);
                getch();
            }
            else printf("Error of getting!\n");
        break;
        };
 
        printf("\n");
    } while (Menu != 3); 
 
    closesocket(clientSock);
    WSACleanup();
    getch();
    return 0;
}
//---------------------------------------------------------------------------
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
13.06.2012, 13:10
Помогаю со студенческими работами здесь

Клиент и сервер не взаимодействуют через интернет
Всем привет.... Начал осваивать сокеты сделал, сервер и клиент, почему на компе эти две программки договариваются, а в инете нет? ...

Сокеты. Клиент-сервер. Как узнать MAC?
Засада!!!!! Не могу получить Mac адрес у клиент-серверного приложения на Winsock. На сервере: получил IP-адрес и доменное имя клиента....

Сокеты и клиент-сервер приложение, как отправлять/принимать байты
Здравствуйте, не могли бы пожалуйста привести пример клиент-сервер приложения. Клиент отправляет запрос, а сервер отправляет ответ в...

Клиент-сервер сокеты
Здравствуйте, учусь работать с сокетами, только начал! Хочу вникнуть, пока не получается, ожидаю вашей помощи в данной ситуации! При...

Сокеты. Клиент-сервер
Добрый день, начал разбирать сетевое программирование, на одном компе у меня все прекрасно работает, я могу с клиента отправить серверу...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Работа со звуком через SDL3_mixer
8Observer8 08.02.2026
Содержание блога Пошагово создадим проект для загрузки звукового файла и воспроизведения звука с помощью библиотеки SDL3_mixer. Звук будет воспроизводиться по клику мышки по холсту на Desktop и по. . .
SDL3 для Web (WebAssembly): Основы отладки веб-приложений на SDL3 по USB и Wi-Fi, запущенных в браузере мобильных устройств
8Observer8 07.02.2026
Содержание блога Браузер Chrome имеет средства для отладки мобильных веб-приложений по USB. В этой пошаговой инструкции ограничимся работой с консолью. Вывод в консоль - это часть процесса. . .
SDL3 для Web (WebAssembly): Обработчик клика мыши в браузере ПК и касания экрана в браузере на мобильном устройстве
8Observer8 02.02.2026
Содержание блога Для начала пошагово создадим рабочий пример для подготовки к экспериментам в браузере ПК и в браузере мобильного устройства. Потом напишем обработчик клика мыши и обработчик. . .
Философия технологии
iceja 01.02.2026
На мой взгляд у человека в технических проектах остается роль генерального директора. Все остальное нейронки делают уже лучше человека. Они не могут нести предпринимательские риски, не могут. . .
SDL3 для Web (WebAssembly): Вывод текста со шрифтом TTF с помощью SDL3_ttf
8Observer8 01.02.2026
Содержание блога В этой пошаговой инструкции создадим с нуля веб-приложение, которое выводит текст в окне браузера. Запустим на Android на локальном сервере. Загрузим Release на бесплатный. . .
SDL3 для Web (WebAssembly): Сборка C/C++ проекта из консоли
8Observer8 30.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
SDL3 для Web (WebAssembly): Установка Emscripten SDK (emsdk) и CMake для сборки C и C++ приложений в Wasm
8Observer8 30.01.2026
Содержание блога Для того чтобы скачать Emscripten SDK (emsdk) необходимо сначало скачать и уставить Git: Install for Windows. Следуйте стандартной процедуре установки Git через установщик. . . .
SDL3 для Android: Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru