您的位置:首页 > 运维架构 > Linux

Linux下使用CURL获取Rest接口数据

2013-09-13 15:10 627 查看
/*

gcc -o test -Wall test.c -lcurl

*/

#include <stdio.h>

#include <string.h>

#include <sys/socket.h>

#include <netdb.h>

#include <arpa/inet.h>

#include <fcntl.h>

#include <sys/select.h>

#include <curl/curl.h>

#include <net/if.h>

#include <sys/ioctl.h>

#define SIZE 1024

#define SERVER_PORT 80

long getlocalhostip(){

int MAXINTERFACES=16;

long ip;

int fd, intrface, retn = 0;

struct ifreq buf[MAXINTERFACES]; ///if.h

struct ifconf ifc; ///if.h

ip = -1;

if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) //socket.h

{

ifc.ifc_len = sizeof buf;

ifc.ifc_buf = (caddr_t) buf;

if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) //ioctl.h

{

intrface = ifc.ifc_len / sizeof (struct ifreq);

while (intrface-- > 0)

{

if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))

{

ip=inet_addr( inet_ntoa( ((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr) );//types

break;

}

}

}

close (fd);

}

return ip;

}

union ipu{

long ip;

unsigned char ipchar[4];

};

int main()

{

union ipu iptest;

iptest.ip = getlocalhostip();

//set your url

char ipstr[100] = "http://172.18.200.88/mod/experiment/receivevm/api.php?ip=";

char ipstritem[3];

char joinstr[] = ".";

int i=0;

for(; i<4; i++){

if(i!=0)

strcat(ipstr, joinstr);

sprintf(ipstritem, "%d", iptest.ipchar[i]);

strcat(ipstr, ipstritem);

}

//printf("%s \n", ipstr);

CURL *curl;

CURLcode res;

curl = curl_easy_init();

if(curl!=NULL)

{

curl_easy_setopt(curl, CURLOPT_URL, ipstr);

res = curl_easy_perform(curl);

curl_easy_cleanup(curl);

}

return 0;

}

CURL真的很好要,不过windows下使用wininet也是比较方便的。如果你需要代码统一,而且方便以后维护的话,可以都使用CRUL。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: