1. 程式人生 > >Linux下使用CURL獲取Rest介面資料

Linux下使用CURL獲取Rest介面資料

/*
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。