我正在使用套接字编程和 C 编写一个简单的代理。
我在从网络服务器获取 HTTP 响应时遇到问题。当我运行此代码并尝试访问 cisco.com 网站时,我的程序给了我一个分段错误错误。
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
int main()
{
int serverSocket;
char ip[INET_ADDRSTRLEN];
int i;
int j;
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serverAddress ;
char pageFilter[] = "HTTP/1.1 302 Found\n\n<html><head><title>this web page is filter !..!</title></head><body><h1>This page in filter</h1><p><h3>Please Leave This site and get out of here!</h3></p></body></html>";
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(9090);
bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
listen(serverSocket, 20);
while (1)
{
int clientSocket ;
int size;
struct sockaddr_in clientAddress;
char * pch;
char * site;
char buffer[9000];
size = sizeof(clientAddress);
clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddress, &size);
recv(clientSocket, buffer, sizeof(buffer), 0);
site = strstr(buffer, "yahoo.com");
if(site != NULL)
{
send(clientSocket, pageFilter, sizeof(pageFilter) ,0);
close(clientSocket);
}
else
{
int middleSocket;
char buf[128];
char response[10000];
struct sockaddr_in middleAddress;
struct hostent *he;
struct in_addr **addr_list;
char site[] = "cisco.com";
middleSocket = socket(AF_INET, SOCK_STREAM, 0);
middleAddress.sin_family = AF_INET;
middleAddress.sin_port = htons(80);
he = gethostbyname(site);
addr_list = (struct in_addr **)he -> h_addr_list;
middleAddress.sin_addr.s_addr = inet_addr(inet_ntoa(*addr_list[0]));
connect(middleSocket, (struct sockaddr *)&middleAddress, sizeof(middleAddress));
send(middleSocket, buffer, sizeof(buffer),0);
while((unsigned)strlen(buf) != 0)
{
recv(middleSocket, buf, sizeof(buf), 0);
strcat(response,buf);
}
send(clientSocket, response, strlen(response),0);
close(clientSocket);
}
}
return 0;
}