Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <assert.h>
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <string.h>
- #include <stdlib.h>
- #include <netinet/in.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #define STR "Hello tcp world\n"
- #define pexit(x) \
- do { \
- perror(x); \
- exit(EXIT_FAILURE); \
- } while (0)
- static struct sockaddr_in saddr;
- int main(int argc, char **argv)
- {
- int sock, clisock;
- if (argc < 2) {
- printf("Usage: %s FILE_TO_SERV [PORT]", argv[0]);
- exit(EXIT_FAILURE);
- }
- assert(argv[1]);
- sock = socket(AF_INET, SOCK_STREAM, 0);
- saddr.sin_family = AF_INET;
- saddr.sin_addr.s_addr = htonl(INADDR_ANY);
- if (argc == 3)
- saddr.sin_port = htons(atoi(argv[2]));
- else
- saddr.sin_port = htons(80);
- if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)))
- pexit("bind");
- if (listen(sock, 10))
- pexit("listen");
- for (;;) {
- FILE *fp;
- struct stat s;
- #define LBUFLEN 256
- char httpheader_buf[LBUFLEN];
- char linebuf[LBUFLEN];
- int filesiz;
- if ((clisock = accept(sock, NULL, NULL)) == -1) {
- perror("accept");
- continue;
- }
- puts("New connection");
- while (stat(argv[1], &s))
- sleep(1);
- puts("Sending file contents");
- fp = fopen(argv[1], "r");
- if (!fp) {
- perror("fopen");
- continue;
- }
- fseek(fp, 0L, SEEK_END);
- filesiz = ftell(fp);
- fseek(fp, 0L, SEEK_SET);
- snprintf(httpheader_buf, LBUFLEN,
- "HTTP/1.1 200 OK\r\n"
- "Content-Type: text/html; charset=UTF-8\r\n"
- "Content-Length: %d\r\n"
- "Server: dummy\r\n"
- "\r\n", filesiz);
- send(clisock, httpheader_buf, strlen(httpheader_buf), 0);
- do {
- fgets(linebuf, LBUFLEN, fp);
- send(clisock, linebuf, strlen(linebuf), 0);
- } while (!feof(fp));
- close(clisock);
- fclose(fp);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement