first commit
This commit is contained in:
67
server.c
Normal file
67
server.c
Normal file
@@ -0,0 +1,67 @@
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define PORT 6008
|
||||
#define BACKLOG 16
|
||||
#define RECV_BUF 1024
|
||||
|
||||
int main() {
|
||||
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
int opt = 1;
|
||||
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
|
||||
|
||||
struct sockaddr_in addr = {0};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = INADDR_ANY;
|
||||
addr.sin_port = htons(PORT);
|
||||
|
||||
bind(server_fd, (struct sockaddr *)&addr, sizeof(addr));
|
||||
listen(server_fd, BACKLOG);
|
||||
|
||||
printf("listening port %d\nbacklog %d\nrecv buffer %d\n", PORT, BACKLOG, RECV_BUF);
|
||||
|
||||
char buf[RECV_BUF];
|
||||
const char *hdr = "X-Forwarded-For:";
|
||||
const size_t hdrlen = strlen(hdr);
|
||||
|
||||
while(1) {
|
||||
int client = accept(server_fd, NULL, NULL);
|
||||
if (client < 0) continue;
|
||||
ssize_t r = recv(client, buf, sizeof(buf) -1, 0);
|
||||
if (r <= 0) { close(client); continue; }
|
||||
buf[r] = 0;
|
||||
|
||||
//find header
|
||||
char *ip = NULL;
|
||||
for (ssize_t i = 0; i < r - (ssize_t)hdrlen; ++i) {
|
||||
if (strncasecmp(buf + i, hdr, hdrlen) == 0) {
|
||||
ip = buf + i + hdrlen;
|
||||
while (*ip == ' ' || *ip == '\t') ip++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
//find end
|
||||
char *end = ip;
|
||||
if (ip) {
|
||||
while (*end && *end != '\r' && *end != '\n') end++;
|
||||
*end = 0;
|
||||
}
|
||||
|
||||
//response
|
||||
const char *head = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: ";
|
||||
char lenbuf[32];
|
||||
int iplen = ip ? strlen(ip) : 0;
|
||||
int len = snprintf(lenbuf, sizeof(lenbuf), "%d\r\n\r\n", iplen);
|
||||
|
||||
send(client, head, strlen(head), 0);
|
||||
send(client, lenbuf, len, 0);
|
||||
if (iplen > 0) send(client, ip, iplen, 0);
|
||||
|
||||
close(client);
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user