我正在编写一个客户端程序,它建立套接字,连接到远程服务器并发出HTTP请求。但是,我似乎无法连接到远程服务器。无法通过套接字连接到HTTP服务C
我相信我所做的一切都对,甚至为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;
}
你错过了注射马力到远程:'BCOPY((字符*)HP-> H_ADDR,(字符*)&remote.sin_addr.s_addr,HP- >长度h_length); ' –
我刚刚尝试过,但仍无法连接。如果我使用'memcpy'而不是重要吗? – Delfino
就在连接之前,连接完成。你如何检查你是否连接? –