我正在编写一个客户端程序,它建立套接字,连接到远程服务器,并发出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;
}
答案 0 :(得分:1)
我明白了
问题在于
行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;
}
答案 1 :(得分:0)
这样做:
remote.sin_port = ntohs(se->s_port);
remote.sin_family = AF_INET;
remote.sin_addr = *((struct in_addr *) hp->h_addr);
应该这样做。连接后请参阅\ r \ n \ r \ n:关闭。
snprintf(http_msg, 256, "GET /%s/%s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", path, fname, host);