首页 热点资讯 义务教育 高等教育 出国留学 考研考公

linux中怎么访问一个URL,并将自己的IP传过去

发布网友 发布时间: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;
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com