1

我想将访问我的端口 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 应该在客户端浏览器地址栏中更改...我该如何实现?..请提供示例代码...

4

1 回答 1

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);
于 2012-08-07T07:53:30.523 回答