我想将访问我的端口80的客户端重定向到某个URL [例如:www.google.com]。并且还需要在浏览器地址栏中更改重定向的URL。
目前我正在使用以下代码
#include<netinet/in.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
int main() {
int create_socket, new_socket;
socklen_t addrlen;
int bufsize = 1024;
char *buffer = malloc(bufsize);
struct sockaddr_in address;
if ((create_socket = socket(AF_INET, SOCK_STREAM, 0)) > 0){
printf("The socket was created\n");
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(15000);
if (bind(create_socket, (struct sockaddr *) &address, sizeof(address)) == 0){
printf("Binding Socket\n");
}
while (1) {
if (listen(create_socket, 10) < 0) {
perror("server: listen");
exit(1);
}
if ((new_socket = accept(create_socket, (struct sockaddr *) &address, &addrlen)) <
0) {
perror("server: accept");
exit(1);
}
if (new_socket > 0){
printf("The Client is connected...\n");
}
recv(new_socket, buffer, bufsize, 0);
printf("%s\n", buffer);
write(new_socket, "hello world\n", 12);
close(new_socket);
}
close(create_socket);
return 0;
}
此代码仅在浏览器窗口中打印hello world。但我需要的是,客户端应该重定向到其他URL,并且应该在客户端浏览器地址栏中更改重定向的URL ...我怎样才能实现这一点?..请提供示例代码...
答案 0 :(得分:1)
变化: -
write(new_socket, "hello world\n", 12);
到
write(new_socket, "HTTP/1.1 301 Moved Permanently\r\nLocation: http://www.google.com\r\n <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"><html><head><title>Your Page Title</title><meta http-equiv=\"REFRESH\" content=\"0;url=http://www.google.com\"></HEAD><BODY>Optional page text here.</BODY></HTML>", 326);