首页 > 编程语言 >c\c++实现天气数据获取

c\c++实现天气数据获取

时间:2022-08-16 16:34:34浏览次数:63  
标签:const addr 天气 c++ char 获取 fd location SOCKET

#include <iostream>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

using namespace std;

const char* host = "api.seniverse.com";
const char* key = "SmKNAkNDNgy0VQHrh";
//const char* location = "ip";
const char* language = "zh-Hans";
char _url[100] = { 0 };

char* generateUrl(const char* key, const char* location, const char* language)
{
	sprintf(_url, "GET /v3/weather/now.json?key=%s&location=%s&language=%s&unit=c\r\n\r\n", 
			key, location, language);
	return _url;
}

SOCKET connetToHost(const char* host, unsigned int port)
{
	//connet to the server

	WSADATA data;
	WSAStartup(MAKEWORD(2, 2), &data);

	//1.create socket
	SOCKET fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == INVALID_SOCKET)
	{
		printf("socket failed, %d\n", WSAGetLastError());
		return INVALID_SOCKET;
	}

	//2.bind
	SOCKADDR_IN addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	//method 1, at main use truly ip
	//addr.sin_addr.S_un.S_addr = inet_addr(host);
	//method 2, use dns to get ip by name
	hostent *hostent =  gethostbyname(host);
	if (hostent)
		memcpy(&addr.sin_addr, hostent->h_addr_list[0], sizeof(addr.sin_addr));
	else
	{
		printf("dns failed\n");
		return INVALID_SOCKET;
	}

	//3.connet
	//in cpp, usually return 0 is right
	if (connect(fd, (SOCKADDR*)&addr, sizeof(addr)) != 0)
	{
		printf("connect failed %d\n", WSAGetLastError());
		return INVALID_SOCKET;
	}
	return fd;
}

int main()
{
	SOCKET fd = connetToHost("116.62.81.138", 80);
	if (fd != INVALID_SOCKET)
		printf("connect successfully\n");

	printf("please input city name, eg: shanghai\n");
	char location[30];
	scanf("%s", location);

	char* url = generateUrl(key, location, language);
	if (send(fd, url, strlen(url), 0) <= 0)
		printf("send failed %d\n", WSAGetLastError());
	else
	{
		char buff[BUFSIZ] = {0};
		if (recv(fd, buff, BUFSIZ, 0) <= 0)
			printf("recv failed %d\n", WSAGetLastError());
		else
		{
			puts(buff);
			//save in file
			FILE* fp = fopen("weather.json", "w");
			if (!fp)
				perror("create file failed\n");
			else
				fwrite(buff, sizeof(char), strlen(buff), fp);
			fclose(fp);
		}
	}

	closesocket(fd);

	return 0;
}

 

标签:const,addr,天气,c++,char,获取,fd,location,SOCKET
From: https://www.cnblogs.com/chr1ce/p/16592027.html

相关文章