gpt4 book ai didi

c - 使用 gethostbyname 时出现段错误

转载 作者:行者123 更新时间:2023-11-30 15:16:33 26 4
gpt4 key购买 nike

我正在尝试创建一个代理服务器,它接受来自客户端的请求,并在收到来自服务器的消息后将响应发送回客户端。但程序出现段错误。

我的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main(int argc,char *argv[])
{
struct sockaddr_in server,client;
struct hostent *host;
int s1,s2,s3,len;
int port;
char ip[100];
char path[100];
int p;
int n;
char buffer[500];
char site[500];
port = atoi(argv[1]);

bzero((char *)&server,sizeof(server));
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
server.sin_family = AF_INET;
s1 = socket(AF_INET,SOCK_STREAM,0);

if(bind(s1,(struct sockaddr *)&server,sizeof(server)) == -1) {
perror("can't bind");
exit(1);
}

if(listen(s1,10) == -1) {
perror("coudnt't listen");
exit(1);
}
len = sizeof(client);
s2 = accept(s1,(struct sockaddr *)&client,&len);
if(s2 == -1) {
perror("coudnt aceept");
exit(1);
}
memset(buffer,0,sizeof(buffer));
n = recv(s2,buffer,500,0);
if(n < 0) {
perror("not recieved");
exit(1);
}

sscanf(buffer, "http://%99[^:]:%99d/%99[^\n]", ip, &p, path);
bzero((char *)&client,sizeof(client));
client.sin_port = htons(80);
host = gethostbyname(ip);
bcopy((char *)host->h_addr,(char *)&client.sin_addr.s_addr,host->h_length);
client.sin_family = AF_INET;
s3 = socket(AF_INET,SOCK_STREAM,0);


if(connect(s3,(struct sockaddr *)&client,sizeof(client)) == -1) {
perror("can't connect\n");
exit(1);
}
sprintf(site,"GET http://%s/ HTTP/1.0\n\n",ip);
n = send(s3,site,strlen(site),0);
if(n < 0) {
perror("message not sent");
exit(1);
}
while(1) {
memset(site,0,sizeof(site));
n = recv(s3,site,500,0);
if(n < 0) {
perror("coudnot read");
exit(1);
}
site[n] = '\0';
send(s2,site,strlen(site),0);
}
close(s1);
close(s2);
return 0;

}

错误似乎来自gethostbyname(ip)因为当我使用gethostbyname("www.iiita.ac.in")时,它有效。

最佳答案

gethostbyname 在发生错误时返回空指针,因此 host->h_addr 是空取消引用。

使用前需要检查host是否为NULL

参见http://man7.org/linux/man-pages/man3/gethostbyname.3.html

关于c - 使用 gethostbyname 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33026204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com