天天看點

使用libcurl實作udp通信

使用libcurl實作udp通信,網絡另一端為192.168.31.199:6000,發送資料為hello xujun

#include <curl/curl.h>
#include <string.h>
//#include <sys/socket.h>

curl_socket_t opensocket (void *clientp,
                            curlsocktype purpose,
                            struct curl_sockaddr *address)
{
	address->socktype = SOCK_DGRAM;
	//address->protocol = IPPROTO_UDP;
	address->protocol = 0;
	return socket(address->family, address->socktype, address->protocol);
}

int main()
{
	CURLcode res = 0;
	CURL *curl = NULL;
	const char *request = "hello xujun\n";
	size_t iolen;

	curl = curl_easy_init();
	if(curl)
	{
		curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket);
		curl_easy_setopt(curl, CURLOPT_URL, "192.168.31.199:6000");
		curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L);

		res = curl_easy_perform(curl);

		long sockextr;
		curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, &sockextr);

		//curl_easy_send & curl_easy_recv here
		curl_easy_send(curl, request, strlen(request), &iolen);
		curl_easy_cleanup(curl);
	}
	return 0;
}