发布网友 发布时间:2022-04-21 17:51
共1个回答
热心网友 时间:2023-06-23 22:38
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/select.h>
#define SIZE 1024
#define SERVER_PORT 80
int main(int argc, char *argv[])
{
int socket_fd, count;
char buf[SIZE];
struct sockaddr_in s_addr;
struct hostent *hent;
fd_set fdset;
struct timeval time_val;
if (argc != 2)
{
printf("usage: %s hostname\n", argv[0]);
return -1;
}
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd == -1)
{
printf("socket failed!\n");
return -1;
}
hent = gethostbyname(argv[1]);
bzero(&s_addr, sizeof(struct sockaddr_in));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(SERVER_PORT);
s_addr.sin_addr.s_addr = inet_addr(inet_ntop(hent->h_addrtype, hent->h_addr_list[0], buf, sizeof(buf)));
connect(socket_fd, (struct sockaddr*)(&s_addr), sizeof(struct sockaddr));
count = snprintf(buf, SIZE, "GET / HTTP/1.1\r\nhost:%s\r\n\r\n", argv[1]);
write(socket_fd, buf, count);
FD_ZERO(&fdset);
FD_SET(socket_fd, &fdset);
time_val.tv_sec = 9;
time_val.tv_usec = 0;
count = select(socket_fd + 1, &fdset, NULL, NULL, &time_val);
if (count == 0)
{
printf("timeout\n");
return -1;
}
fcntl(socket_fd, F_SETFL, O_NONBLOCK);
while ((count = read(socket_fd, buf, SIZE - 1)) > 0)
{
buf[count] = 0;
printf("%s\n", buf);
}
close(socket_fd);
return 0;
}