#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <arpa/inet.h>#define SOH 0x01#define STX 0x02#define ETX 0x03#define ETB 0x17#define EOT 0x04#define SYN 0x16#define DLE 0x10#define NAK 0x15#define ACK0 0x1000#define ACK1 0x1001intmain(intargc, char*argv[]) {
if (argc!=2) {
printf("Usage: %s <filename>\n", argv[0]);
return1;
}
constchar*filename=argv[1];
FILE*file=fopen(filename, "rb");
if (file==NULL) {
printf("Failed to open file: %s\n", filename);
return1;
}
intsock=socket(AF_INET, SOCK_STREAM, 0);
if (sock==-1) {
printf("Failed to create socket\n");
fclose(file);
return1;
}
structsockaddr_inserver_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
server_addr.sin_port=htons(3568);
if (connect(sock, (structsockaddr*)&server_addr, sizeof(server_addr)) ==-1) {
printf("Failed to connect to the server\n");
fclose(file);
close(sock);
return1;
}
intsequence=0;
charbuffer[1024];
size_tread_bytes;
intack_sequence=0;
intrecv_ack;
buffer[0] =SYN;
buffer[1] =SYN;
write(sock, buffer, 2);
if (read(sock, &recv_ack, sizeof(recv_ack)) !=sizeof(recv_ack)) {
printf("Failed to receive ACK\n");
fclose(file);
close(sock);
return1;
}
if (ntohs(recv_ack) !=ACK0) {
printf("Failed to establish connection\n");
fclose(file);
close(sock);
return1;
}
while ((read_bytes=fread(buffer, 1, sizeof(buffer), file)) >0) {
size_ttotal_bytes=read_bytes;
if (sequence==0)
buffer[total_bytes++] =SOH;
elsebuffer[total_bytes++] =STX;
inti, j;
for (i=1, j=1; i<read_bytes; i++, j++) {
if (buffer[i] ==SYN||buffer[i] ==ETB||buffer[i] ==ETX||buffer[i] ==DLE) {
buffer[j++] =DLE;
}
buffer[j] =buffer[i];
}
read_bytes=j;
shortbcc=0;
for (i=0; i<read_bytes; i++) {
bcc+=buffer[i];
}
buffer[total_bytes++] =ETX;
buffer[total_bytes++] =bcc>>8;
buffer[total_bytes++] =bcc&0xFF;
if (write(sock, buffer, total_bytes) !=total_bytes) {
printf("Failed to send data\n");
fclose(file);
close(sock);
return1;
}
if (read(sock, &recv_ack, sizeof(recv_ack)) !=sizeof(recv_ack)) {
printf("Failed to receive ACK\n");
fclose(file);
close(sock);
return1;
}
if (ntohs(recv_ack) !=ACK0+sequence) {
printf("Failed to receive ACK\n");
fclose(file);
close(sock);
return1;
}
sequence=1-sequence;
}
buffer[0] =EOT;
if (write(sock, buffer, 1) !=1) {
printf("Failed to send EOT\n");
fclose(file);
close(sock);