gpt4 book ai didi

无法通过套接字连接到 HTTP 服务 - C

转载 作者:行者123 更新时间:2023-11-30 15:21:47 28 4
gpt4 key购买 nike

我正在编写一个客户端程序,用于建立套接字、连接到远程服务器并发出 HTTP 请求。但是,我似乎无法连接到远程服务器。

我相信我已经做对了一切,甚至为 sockaddr_in 设置了正确的端口号,但我仍然无法连接。

我错过了什么?

#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
FILE *fout;

int i, c, sk;
char *tk, host[64], path[64], fname[64], http_msg[256], buf[1024];

struct sockaddr_in remote;
struct hostent *hp;
struct servent *se;

if(argc != 2)
{
printf("Invalid number of arguments. Program terminating...\n");
exit(1);
}

sk = socket(AF_INET, SOCK_STREAM, 0);
remote.sin_family = AF_INET;

c = 0;
tk = strtok(argv[1], "/");
while(tk != NULL)
{
if(c == 0)
strcpy(host, tk);
else if(c == 1)
strcpy(path, tk);
else
strcpy(fname, tk);
++c;
tk = strtok(NULL, "/");
}

snprintf(http_msg, 256, "GET /%s/%s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\n", path, fname, host);

hp = gethostbyname(host);
if(hp == NULL)
{
printf("Can't find host %s. Program terminating...\n", host);
exit(1);
}

se = getservbyname("http", "tcp");
remote.sin_port = ntohs(se->s_port);

if(connect(sk, (struct sockaddr*)&remote, sizeof(remote)) < 0)
{
printf("Connection attempt failed. Program terminating...\n");
exit(1);
}

send(sk, http_msg, sizeof(http_msg) + 1, 0);
recv(sk, buf, sizeof(buf), 0);
printf("%s\n", buf);

return 0;
}

最佳答案

我明白了

问题出在线路上

remote.sin_port = ntohs(se->s_port);

您不需要转换它。这段代码对我有用:

if(argc != 2)                                                              
{
printf("Invalid number of arguments. Program terminating...\n");
exit(1);
}

bzero(&remote, sizeof(remote));
sk = socket(AF_INET, SOCK_STREAM, 0);
remote.sin_family = AF_INET;

c = 0;
tk = strtok(argv[1], "/");
while(tk != NULL)
{
if(c == 0)
strcpy(host, tk);
else if(c == 1)
strcpy(path, tk);
else
strcpy(fname, tk);
++c;
tk = strtok(NULL, "/");
}

snprintf(http_msg, 256, "GET /%s/%s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", path, fname, host);

hp = gethostbyname(host);
if(hp == NULL)
{
printf("Can't find host %s. Program terminating...\n", host);
exit(1);
}

se = getservbyname("http", "tcp");
printf("%d port\n", ntohs(se->s_port));
remote.sin_port = se->s_port;
bcopy((char *)hp->h_addr, (char *)&remote.sin_addr.s_addr, hp->h_length);

if(connect(sk, (struct sockaddr*)&remote, sizeof(remote)) < 0)
{
printf("Connection attempt failed. Program terminating...\n");
exit(1);
}

send(sk, http_msg, sizeof(http_msg) + 1, 0);
recv(sk, buf, sizeof(buf), 0);
printf("%s\n", buf);

return 0;

}

关于无法通过套接字连接到 HTTP 服务 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29483479/

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