C发送http请求
来源:互联网 发布:比特币是网络传销吗 编辑:程序博客网 时间:2024/05/17 14:15
C语言发送http请求和普通的socket通讯,原理是一样的.无非就三步connect()连上服务器,send()发送数据,recv()接收数据.只不过发送的数据有特定的格式.下面的是简单发送一个http请求的例子
#include <netinet/in.h>#include <sys/socket.h>#include <netdb.h>#include <unistd.h>#include <string.h>#include <stdio.h>int main(int argc, char **argv){ /* 构造查询包 */ const char quary[] = "GET / HTTP/1.0\r\n" "Host: blog.csdn.net\r\n" "\r\n"; const char hostname[] = "blog.csdn.net"; struct sockaddr_in sin; struct hostent *h; const char *cp; int fd; ssize_t n_written, remaining; char buf[1024]; /* 查找该域名的地址 */ h = gethostbyname(hostname); if(h == NULL) { fprintf(stderr, "Couldn't lookup %s:%s\n", hostname, hstrerror(h_errno)); return 1; } if (h->h_addrtype != AF_INET) { fprintf(stderr, "No ipv6 support, sorry.\n"); return 1; } /* 创建一个套接字用来连接服务器 */ fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { perror("socket"); return 1; } /* 连接到服务器 */ sin.sin_family = AF_INET; sin.sin_port = htons(80); sin.sin_addr = *(struct in_addr*)h->h_addr; if (connect(fd, (struct sockaddr *)&sin, sizeof(sin))) { perror("connect"); close(fd); return 1; } /* 发送请求 */ cp = quary; remaining = strlen(quary); while(remaining) { n_written = send(fd,cp, remaining, 0); if (n_written <= 0) { perror("send"); return 1; } remaining -= n_written; cp += n_written; } /* 获取响应 */ while(1) { ssize_t result = recv(fd, buf, sizeof(buf), 0); if (result == 0) { break; } else if (result < 0) { perror("recv\n"); close(fd); return 1; } fwrite(buf, 1, result, stdout); } close(fd); return 0;}
1 0
- C发送http请求
- C发送http请求
- c socket 发送http请求
- linux C发送 http 请求
- linux C发送 http 请求
- C socket 发送HTTP请求
- C实现通过sock发送http请求
- c socket 发送http请求 (一)
- C#发送HTTP请求
- java 发送http请求
- socket 发送http请求
- python发送HTTP请求
- 异步发送HTTP请求
- python发送HTTP请求
- Qt发送HTTP请求
- socket发送http请求
- 发送http请求
- JAVA发送HTTP请求
- 【codeforces 366A Dima and Guards】
- 数据结构-栈的应用-算术表达式小括号匹配
- 初学者之小甲鱼重载方法,静态成员
- knockoutjs valueAllowUnset 属性
- 日记区
- C发送http请求
- NOIP2012d2t2 国王游戏
- 【转载】 Android安全攻防战,反编译与混淆技术完全解析(上)
- 我的ListView
- Dima and Guards
- Android 动画之属性动画
- 378.leetcode Kth Smallest Element in a Sorted Matrix(medium)[堆求第K小的 ]
- 学习ios(必看经典)牛人40天精通iOS开发的学习方法
- 江南水墨画