/*
*Obtain CM status with socket!
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define CM_ip "192.168.100.1"
#define CM_pt 80
/* make sure buf size large enough */
/*
Example : Build_Http_Request("192.168.100.1", "/", buffer);
Build_Http_Request("192.168.100.1", "/index.php", buffer);
*/
#define Build_Http_Request(server_ip,url,buf) \
do{ \
assert((buf)!=NULL); \
memset((buf), 0x00, sizeof(buf)); \
sprintf((buf), "GET "); \
strcat((buf), (url)); \
strcat((buf), " HTTP/1.1\r\n"); \
strcat((buf), "Host:"); \
strcat((buf), (server_ip)); \
strcat((buf), "\r\n"); \
strcat((buf), "Accept: */*\r\n"); \
strcat((buf), "User-Agent: Mozilla/4.0(compatible)\r\n"); \
strcat((buf), "connection:Keep-Alive\r\n"); \
strcat((buf), "\r\n\r\n"); \
}while(0)
int main(int argc, char *argv[])
{
int sockfd;
int readlen = 0;
char szbuf[4096];
struct sockaddr_in addr;
struct hostent *host;
sockfd = socket(AF_INET,SOCK_STREAM,0);
if (sockfd<0)
{
printf("Open socket failed!\n");
return 1;
}
bzero(&addr,sizeof(struct sockaddr_in));
addr.sin_family=AF_INET;
addr.sin_port=htons(CM_pt);
if (inet_aton(CM_ip,&addr.sin_addr) == 0)
{
host = gethostbyname(CM_ip);
if (host!=NULL)
{
printf("Illegal HostName!\n");
return 1;
}
addr.sin_addr=*(struct in_addr *)(host->h_addr_list[0]);
}
printf("Connect ip : %d - %s\n", addr.sin_addr, inet_ntoa(addr.sin_addr));
if (connect(sockfd, (struct sockaddr *)(&addr), sizeof(struct sockaddr) )==-1)
{
printf("Connect server failed!\n");
goto ERROR;
}
Build_Http_Request(CM_ip, "/", szbuf);
if (send(sockfd, szbuf, strlen(szbuf),0) == -1)
{
printf("Send data failed!\n");
goto ERROR;
}
printf("\nSend data :\n%s\n",szbuf);
sleep(1);
RECV:
memset(szbuf,0x00,2048);
if ( (readlen=recv(sockfd, szbuf, 4096, 0)) == -1)
{
printf("Recv data failed!\n");
goto ERROR;
}
printf("Good : get web sucess : [%d]\n", readlen);
printf("%s", szbuf);
printf("Good : get end!\n");
if (readlen > 0) goto RECV;
ERROR:
close(sockfd);
return 0;
}
阅读(1533) | 评论(0) | 转发(0) |