C socket post数据到url
#define HOST_SERVER_IP "192.168.1.15" #define HOST_PORT 80 int gsh_post_clients(const char* sn, const char* ip) { if (NULL == sn || NULL == ip) { return -1; } int iSocketId = -1; int iDataLength = 0; int iConnectId = 1; char acHeader[BUFSIZ] = ""; char acRequestData[BUFSIZ] = ""; char *pcRequestDataLength = ""; struct sockaddr_in stSocketAddr; char text[BUFSIZ]; /* * 设定socket参数 */ iSocketId = socket(AF_INET, SOCK_STREAM, 0); if (-1 == iSocketId) { printf("socket is wrong!"); return -1; } stSocketAddr.sin_family = AF_INET; stSocketAddr.sin_port = htons(HOST_PORT); inet_aton(HOST_SERVER_IP, &stSocketAddr.sin_addr); /* * 组织发送到web服务器的信息 */ strcat(acRequestData, "sn="); strcat(acRequestData, sn); strcat(acRequestData, "&"); strcat(acRequestData, "ip="); strcat(acRequestData, ip); pcRequestDataLength = (char *)malloc(128); iDataLength = strlen(acRequestData); sprintf(pcRequestDataLength, "%d", iDataLength); strcat(acHeader, "POST "); strcat(acHeader, "/api.php"); strcat(acHeader, " HTTP/1.1\r\n"); strcat(acHeader, "Accept: */*\r\n"); strcat(acHeader, "Referer: http://"); strcat(acHeader, HOST_SERVER_IP); strcat(acHeader, "/api.php\r\n"); strcat(acHeader, "Accept-Language: zh-cn\r\n"); strcat(acHeader, "Content-Type: application/x-www-form-urlencoded\r\n"); strcat(acHeader, "HOST: "); strcat(acHeader, HOST_SERVER_IP); strcat(acHeader, "\r\n"); strcat(acHeader, "Connection: Keep-Alive\r\n"); strcat(acHeader, "Content-Length: "); strcat(acHeader, pcRequestDataLength); strcat(acHeader, "\n\n"); //必须为 \n\n,不能是 \r\n strcat(acHeader, acRequestData); strcat(acHeader, "\r\n\r\n"); /* * 连接到服务器,发送请求 */ iConnectId = connect(iSocketId,(struct sockaddr *)&stSocketAddr, sizeof(struct sockaddr_in)); if (0 != iConnectId) { printf("connect is fail!"); return -1; } if (strlen(acHeader) != send(iSocketId, acHeader, strlen(acHeader), 0)) { printf("send data is fail!"); return -1; } while(recv(iSocketId, text, BUFSIZ, 0) > 0) { printf("%s", text); } close(iSocketId); return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。