c Get方式请求网络接口

时间:2022-11-20 15:21:44
#include <stdio.h>
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <string.h>
 #include <arpa/inet.h>
 #include <netdb.h>
 #include <netinet/in.h>
 #include <stdlib.h>
 #include <time.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <linux/if.h>


/*
 *功能: [fGeturl] c语言访问url 
 * 参数: url:地址  nPort:地址的端口
 * 返回值: 0:成功 -1:失败
 * 备注:端口注意 默认的都是80
 */
#define BUFSIZE 0xF000
 int fGeturl(char* url,int nPort, char *pResult){
        int cfd;
        struct sockaddr_in cadd;
        struct hostent *pURL = NULL;
        char myurl[BUFSIZE];
        char *pHost = 0;
        char host[BUFSIZE],GET[BUFSIZE];
        char request[BUFSIZE];
        static char text[BUFSIZE];
        int i,j;
        //分离主机中的主机地址和相对路径
        memset(myurl,0,BUFSIZE);
        memset(host,0,BUFSIZE);
        memset(GET,0,BUFSIZE);
        strcpy(myurl,url);
        for(pHost = myurl;*pHost != '/' && *pHost != '\0' &&*pHost != ':';++pHost);
        //获取相对路径保存到GET中
        if((int)(pHost-myurl) == strlen(myurl)){
                strcpy(GET,"/");//即url中没有给出相对路径,需要自己手动的在url尾部加上/
        }else{
if(*pHost == ':'){
sscanf(pHost,":%*d%s", GET);
}else{
strcpy(GET,pHost);//地址段pHost到strlen(myurl)保存的是相对路径
}
        }
        //将主机信息保存到host中
        //此处将它置零,即它所指向的内容里面已经分离出了相对路径,剩下的为host信
//息(从myurl到pHost地址段存放的是HOST)
        *pHost = '\0';
        strcpy(host,myurl);
        //设置socket参数
        if(-1 == (cfd = socket(AF_INET,SOCK_STREAM,0))){
                printf("create socket failed of client!\n");
                exit(-1);
        }
        pURL = gethostbyname(host);//将上面获得的主机信息通过域名解析函数获得域>名信息
        
        //设置IP地址结构
        bzero(&cadd,sizeof(struct sockaddr_in));
        cadd.sin_family = AF_INET;
        cadd.sin_addr.s_addr = *((unsigned long*)pURL->h_addr_list[0]);
        cadd.sin_port = htons(nPort);
        //向WEB服务器发送URL信息
        memset(request,0,BUFSIZE);
        strcat(request,"GET ");
        strcat(request,GET);
        strcat(request," HTTP/1.1\r\n");//至此为http请求行的信息
        strcat(request,"HOST: ");
        strcat(request,host);
        strcat(request,"\r\n");
        strcat(request,"Cache-Control: no-cache\r\n\r\n");
        printf("====== Host:%s, get:%s ======\n", host,GET);
        //连接服务器
int cc;
        if(-1 == (cc = connect(cfd,(struct sockaddr*)&cadd,(socklen_t)sizeof(cadd)))){
                printf("connect failed of client!\n");
                exit(1);
        }
        printf("connect success!\n");
 
        //向服务器发送url请求的request
        int cs;
        if(-1 == (cs = send(cfd,request,strlen(request),0))){
                printf("向服务器发送请求的request失败!\n");
                exit(1);
        }
        printf("发送成功,发送的字节数:%d\n",cs);
 
        //客户端接收服务器的返回信息
        memset(text,0,BUFSIZE);
        int cr;
        if(-1 == (cr = recv(cfd,text,BUFSIZE,0))){
strcpy(pResult,"recieve failed!");
printf("recieve failed!\n");
exit(1);
        }else{
strcpy(pResult,text);
printf("receive succecc!\n");
        }
        close(cfd);
 }
 
 /*
  * 执行系统命令并获取命令的返回结果
  */
 bool fSystemCmd(const char *sCmd,char *sResult){
    //~ cout<<"【Cmd】"<<sCmd <<endl;
    FILE *pf=popen( sCmd, "r");
    fread( sResult,1024,1,pf);
    //~ cout<<"【Result】"<<sResult<<endl<<endl;
    pclose(pf);
    if( 0 == strcmp(sResult, "") )
        return false;
    return true;
}
 
 
 /*
  * 功能:获取本机ip地址
  */
  union ipu{
long ip;
unsigned char ipchar[4];
};
 long fGetlocalhostip(){
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){
ifc.ifc_len = sizeof buf;
ifc.ifc_buf = (caddr_t) buf;
if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)){
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;
}


 void fGetFileTowContent(const char * pPath, char *sResult){
FILE *fp;
char stempstr[1024]="";
fp = fopen(pPath,"r");
fgets(stempstr, 1023, fp);
fgets(sResult, 1023, fp);
fclose(fp);
 }
 
 /*
 *功能: 注册和更新服务器信息
 *参数: sSerialNumber:序列号  nInterval:间隔时间 默认为5分钟
 */
 void fRegisterAndUpdate(char *sSerialNumber, int nInterval=5){
char sUpdateURL[1024] = "";
char sResult[100*1024]="";
char sIP[20]="";
union ipu iptest; ///存储本机ip
///4.0获取本机的公网ip
fSystemCmd("curl members.3322.org/dyndns/getip", sIP);
///5.0获取本机的ip地址
iptest.ip = fGetlocalhostip();
///6.0组合 更新服务器数据的URL
sprintf(sUpdateURL,"www.ledmediasz.com:8801/API/ServerSave.ashx?SerialNumber=%s&LanIp=%u.%u.%u.%u&Interval=%d&WanIp=%s",
sSerialNumber,
iptest.ipchar[0],
iptest.ipchar[1],
iptest.ipchar[2],
iptest.ipchar[3],
nInterval,
sIP);
fGeturl(sUpdateURL,8801,sResult);
//~ printf("[RegisterOR update Result]:%s\n",sResult);

 }
 
 void fForeverRun(){
char sResult[100*1024]="";
int nInterval = 0;
char sSerialNumber[100]="";
char sGetURL[1024] = "";
char sUpdateURL[1024] = "";
char sIP[20]="";
union ipu iptest; ///存储本机ip
///1.0获取SerialNumber
//~ fGetFileTowContent("/home/ledmedia/2016.4.1-5.0安装/TEST_BMP_1/ledad5.0/python/settings.ini", sSerialNumber);
//~ sscanf(sSerialNumber,"SerialNumber=%s",sSerialNumber);
///2.0组合 请求服务器数据的URL
sprintf(sGetURL,"www.ledmediasz.com:8801/API/Detection_updates.ashx?SerialNumber=20161616",sSerialNumber);
//~ sprintf(sGetURL,"www.ledmediasz.com:8801/API/ServerGet.ashx?handle=get&SerialNumber=20161616");
//~ printf("[sSerialNumber]:%s, [URL]:%s\n",sSerialNumber, sGetURL);
//~ fRegisterAndUpdate(sSerialNumber); ///注册
//~ while(1){
///3.0请求服务器 获取时间间隔
fGeturl(sGetURL,8801,sResult) ;
printf("time:%ld, result:%s\n", time(0),sResult);
//~ if(strstr( sResult, "{\"msg\":\"2\"}")){
//~ printf("sSerialNumber:%s, No register server\n", sSerialNumber);
//~ exit(-1);
//~ }
//~ strcpy(sResult,strstr( sResult, "\"Interval\":"));
        //~ sscanf(sResult, "\"Interval\":\"%d\"", &nInterval);
        //~ sleep(nInterval*60);
        //~ printf("time:%ld,interval:%d\n", time(0), nInterval);
        //~ 
        //~ fRegisterAndUpdate(sSerialNumber, nInterval); ///更新
//~ }
 }
int main(int argc,char* argv[])
 {
        //~ geturl("china.huanqiu.com/article/2016-10/9533343.html?from=bdwz",80,sResult);
        fForeverRun();       
        return 0;
 }