重定向到c中的网站

时间:2012-08-16 07:06:06

标签: sockets redirect

我使用以下代码重定向客户端请求。但是,在执行以下操作时,不会重定向客户端。它在浏览器中显示“无法连接”。我使用iptables将客户端重定向到端口8080。并运行以下可执行文件以重定向。如何重定向客户端。请提供解决方案......

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h> 

#include<stdlib.h>

int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr; 

char *reply = "HTTP/1.1 301 Moved Permanently\nServer: Apache/2.2.3\nLocation: 
http://www.google.com\nContent-Length: 1000\nConnection: close\nContent-Type:  
text/html; charset=UTF-8";

char sendBuff[1025];
time_t ticks; 

listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff)); 

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(8080); 


bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); 

listen(listenfd, 10); 

while(1)
{
    connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); 

printf("client connected\n");
    send(connfd, reply, strlen(reply), 0);

    close(connfd);
    sleep(1);
 }
 }

2 个答案:

答案 0 :(得分:0)

请参阅this pagethis page中的示例,以在服务器端构建有效的http响应。然后,在它下面添加你的html主体。

您需要的最低价格

 HTTP/1.1 200 OK
 Content-Length: XXXXX <- put size of the your html body 
 Connection: close
 Content-Type: text/html; charset=UTF-8

答案 1 :(得分:0)

我无法重现您看到的错误。您应该提供更多详细信息(例如,什么样的客户端,iptables规则的确切文本)。对于我的测试,我没有设置任何iptables规则,而是将Firefox 12.0浏览器直接指向localhost:8080

分割您的回复以便更容易阅读,显示:

char *reply =
"HTTP/1.1 301 Moved Permanently\n"
"Server: Apache/2.2.3\n"
"Location: http://www.google.com\n"
"Content-Length: 1000\n"
"Connection: close\n"
"Content-Type: text/html; charset=UTF-8"
;

虽然RFC为行终止符指定了\r\n,但大多数客户端都会接受\n(您没有说明您使用的是哪个客户端)。但是,另外三个明显的问题是最后一行没有终止,响应本身没有以空行终止,而且Content-Length标题为1000,但没有内容。任何这些问题都可能导致客户将响应视为无效并忽略它。

char *reply =
"HTTP/1.1 301 Moved Permanently\r\n"
"Server: Apache/2.2.3\r\n"
"Location: http://www.google.com\r\n"
"Content-Length: 0\r\n"
"Connection: close\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"\r\n"
;

进一步阅读您的代码,您在发送回复后立即关闭连接,而无需先阅读请求。这可能会导致(尽管不太可能)竞争,在请求完全传递到服务器之前关闭连接。然后,当请求到达时,它将触发重置到客户端,并且可以删除响应。因此,您应该添加代码以使回复的传递更加健壮:

printf("client connected\n");
send(connfd, reply, strlen(reply), 0);
shutdown(connfd, SHUT_WR);
while (recv(connfd, sendBuff, sizeof(sendBuff), 0) > 0) {}
close(connfd);

鉴于我无法使用响应重现您的问题,但您也可能没有正确设置iptable重定向规则。