我正在使用套接字编程和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;
}
答案 0 :(得分:0)
首先,捕获recv
的返回值,它指示错误或接收的字节数。
ssize_t n;
n = recv(middleSocket, buf, sizeof(buf) - 1);
请注意,您不应该通过sizeof(buf)
,因为您需要有空间来保证buf
的终止。
检查错误。
if (n == -1) { /* handle error */ }
else if (n == 0) { /* handle empty response */ }
零终止buf
。
buf[n] = '\0';
您的分段错误可能正在发生,因为您在无界字符串上调用strstr
。
答案 1 :(得分:0)
分段错误是由无效的内存访问引起的。阅读更多:http://en.wikipedia.org/wiki/Segmentation_fault
使用GDB查找发生错误时程序正在执行的位置。在此之后,您应该在代码中看到问题。