使用Code::blockswindows下写网络程序

作者

He YiJun – storysnail<at>hotmail.com

   

版权

转载请保留本声明!

本文档包含的原创代码根据General Public License,v3 发布
GPLv3 许可证的副本可以在这里获得:http://www.gnu.org/licenses/gpl.html

本文档根据GNU
Free Documentation License 1.3发布
GFDL1.3许可证的副本可以在这里获得:http://www.gnu.org/licenses/gfdl.html

文中所引用的软件版权详见各软件版权具体声明,文中所提及的所有商标均为各自商标所有人的财产。
作者在此向所有提供过帮助和支持的朋友表示感谢,此致!

更新

2014-11-10

修改版权,增加linux版示例程序

本文已经停止更新,网络开发请参阅msys2开发环境配置

   

前言:

这是一个用来读取指定网页内容的程序。当前还非常原始,但已经能完成基本的功能。未来我会在这个程序的基础上不断扩充,让这个程序变成一个可用的更新检测程序!

一:windows下用Code::blocks开发网络程序

1:
Code::blocks 中新建一个工程
2:
建完工程后点击Project菜单,选择Build
options...
3:
选择Linker
settings标签页,在Other
linker options:中添加:

-lwsock32

二 源代码

  1. /***********************************************************************
  2. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
  3. Eabc-version-verfy.c
  4. Develop Team : ls
  5. Team Leader : He YiJun (storysnail<at>gmail.com)
  6. Main Programmer : He YiJun
  7. Programmer : Ling Ying
  8. Program comments : Ling Ying
  9. Dict Editor : Yang QiuXi
  10. Documents : Ling Ying、 Yang QiuXi
  11. Art Designer : He YiJun
  12. License : GPLv3
  13. Last Update : 2013-02-25
  14. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
  15. *************************************************************************/
  16. #include <windows.h> // 新增 windows.h
  17. #include <winsock2.h>
  18. //#pragma comment(lib, "ws2_32.lib") // For VS
  19. #include <tchar.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <malloc.h>
  23. #include <io.h>
  24. #ifdef _MT
  25. #include <process.h>
  26. #endif
  27. /* DWORD_PTR (pointer precision unsigned integer) is used for integers
  28. * that are converted to handles or pointers
  29. * This eliminates Win64 warnings regarding conversion between
  30. * 32 and 64-bit data, as HANDLEs and pointers are 64 bits in
  31. * Win64 (See Chapter 16). This is enable only if _Wp64 is defined.
  32. */
  33. #if !defined(_Wp64)
  34. #define DWORD_PTR DWORD
  35. #define LONG_PTR LONG
  36. #define INT_PTR INT
  37. #endif
  38. #define MAX_RQRS_LEN 0x1000 //4096
  39. /* Required for sockets */
  40. #define SERVER_PORT 80
  41. typedef struct {
  42. LONG32 rsLen;
  43. BYTE record [MAX_RQRS_LEN];
  44. } RESPONSE;
  45. typedef struct {
  46. LONG32 rqLen;
  47. BYTE record [MAX_RQRS_LEN];
  48. } REQUEST;
  49. #define RQ_SIZE sizeof (REQUEST)
  50. #define RQ_HEADER_LEN RQ_SIZE-MAX_RQRS_LEN
  51. #define RS_SIZE sizeof (RESPONSE)
  52. #define RS_HEADER_LEN RS_SIZE-MAX_RQRS_LEN
  53. static BOOL SendRequest (REQUEST *, SOCKET);
  54. static BOOL ReceiveResponse (RESPONSE *, SOCKET);
  55. static VOID PrintError (LPCTSTR , DWORD , BOOL);
  56. struct sockaddr_in clientSAddr;
  57. int _tmain (int argc, LPSTR argv[])
  58. {
  59. SOCKET clientSock = INVALID_SOCKET;
  60. REQUEST request;
  61. RESPONSE response;
  62. WSADATA WSStartData; /* Socket library data structure */
  63. DWORD conVal;
  64. while (1) {
  65. _tprintf (_T("%s"), _T("\nEnter Command: "));
  66. _fgetts ((char *)request.record, MAX_RQRS_LEN-1, stdin);
  67. /* Get rid of the new line at the end */
  68. /* Messages use 8-bit characters */
  69. request.record[strlen((char *)request.record)-1] = '\0';
  70. if (strcmp ((char *)request.record, "$Quit") == 0)
  71. break;
  72. if (strncmp ((char *)request.record, "GET",3) == 0)
  73. request.record[strlen((char *)request.record)] = '\n';
  74. /* Initialize the WS library. Ver 2.2 */
  75. if (WSAStartup (MAKEWORD (2, 2), &WSStartData) != 0)
  76. PrintError (_T("Cannot support sockets"), 1, TRUE);
  77. /* Connect to the server */
  78. /* Follow the standard client socket/connect sequence */
  79. clientSock = socket(AF_INET, SOCK_STREAM, 0);
  80. if (clientSock == INVALID_SOCKET)
  81. PrintError (_T("Failed client socket() call"), 2, TRUE);
  82. memset (&clientSAddr, 0, sizeof(clientSAddr));
  83. clientSAddr.sin_family = AF_INET;
  84. //clientSAddr.sin_addr.s_addr = htonl(inet_addr ("121.127.248.96"));
  85. clientSAddr.sin_addr.s_addr = inet_addr ("121.127.248.96");
  86. clientSAddr.sin_port = htons(SERVER_PORT);
  87. conVal = connect (clientSock, (struct sockaddr *)&clientSAddr, sizeof(clientSAddr));
  88. if (conVal == SOCKET_ERROR) PrintError (_T("Failed client connect() call)"), 3, TRUE);
  89. SendRequest (&request, clientSock);
  90. ReceiveResponse (&response, clientSock);
  91. shutdown (clientSock, SD_BOTH); /* Disallow sends and receives */
  92. closesocket (clientSock);
  93. WSACleanup();
  94. close (clientSock);
  95. }
  96. _tprintf (_T("\n****Leaving client\n"));
  97. return 0;
  98. }
  99. // GET http://www.7fane.com/test.html
  100. BOOL SendRequest (REQUEST *pRequest, SOCKET sd)
  101. {
  102. /* Send the the request to the server on socket sd */
  103. BOOL disconnect = FALSE;
  104. LONG32 nRemainSend, nXfer;
  105. LPBYTE pBuffer;
  106. //char target[]="GET http://www.7fane.com/test.html\n";
  107. pRequest->rqLen = (DWORD)(strlen ((char *)pRequest->record) + 1);
  108. nRemainSend = pRequest->rqLen;
  109. pBuffer = (LPBYTE)pRequest->record;
  110. _tprintf (_T("%s%s"), _T("\nNow SendRequestMessage: "),pBuffer);
  111. while (nRemainSend > 0 && !disconnect) {
  112. nXfer = send (sd, (char *)pBuffer, nRemainSend, 0);
  113. //nXfer = send (sd, target, strlen(target), 0);
  114. if (nXfer == SOCKET_ERROR) PrintError (_T("client send() failed"), 5, TRUE);
  115. disconnect = (nXfer == 0);
  116. nRemainSend -=nXfer;
  117. pBuffer += nXfer;
  118. _tprintf (_T("%s%d"), _T("\nSend btyes: "),nXfer);
  119. //_tprintf (_T("%s%s"), _T("\nSend content: "),target);
  120. _tprintf (_T("%s%s"), _T("\nSend content: "),pRequest->record);
  121. }
  122. return disconnect;
  123. }
  124. BOOL ReceiveResponse (RESPONSE *pResponse, SOCKET sd)
  125. {
  126. BOOL disconnect = FALSE;
  127. LONG32 nRemainRecv, nXfer;
  128. LPBYTE pBuffer;
  129. _tprintf (_T("%s"), _T("\nNow ReceiveResponseMessage! "));
  130. while(!disconnect) {
  131. /* Read each response and send it to std out.*/
  132. memset (pResponse->record, 0, MAX_RQRS_LEN);
  133. nRemainRecv = MAX_RQRS_LEN;
  134. pBuffer = (LPBYTE)pResponse->record;
  135. while (nRemainRecv > 0 && !disconnect) {
  136. nXfer = recv (sd, (char *)pBuffer, nRemainRecv, 0);
  137. if (nXfer == SOCKET_ERROR) PrintError (_T("client response recv() failed"), 7, TRUE);
  138. disconnect = (nXfer == 0);
  139. nRemainRecv -=nXfer;
  140. pBuffer += nXfer;
  141. if(!disconnect) {
  142. _tprintf (_T("%s[%d]"), _T("\nReceive bytes: "),nXfer);
  143. _tprintf (_T("%s\n%s"), _T("\nReceive content: "),pResponse->record);
  144. }
  145. }
  146. }
  147. return disconnect;
  148. }
  149. VOID PrintError (LPCTSTR userMessage, DWORD exitCode, BOOL printErrorMessage)
  150. {
  151. DWORD eMsgLen, errNum = GetLastError ();
  152. LPTSTR lpvSysMsg;
  153. _ftprintf (stderr, _T("%s\n"), userMessage);
  154. if (printErrorMessage) {
  155. eMsgLen = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  156. NULL, errNum, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
  157. (LPTSTR) &lpvSysMsg, 0, NULL);
  158. if (eMsgLen > 0)
  159. {
  160. _ftprintf (stderr, _T("%s\n"), lpvSysMsg);
  161. }
  162. else
  163. {
  164. _ftprintf (stderr, _T("Last Error Number; %d.\n"), (int)errNum);
  165. }
  166. if (lpvSysMsg != NULL) LocalFree (lpvSysMsg); /* Explained in Chapter 5. */
  167. }
  168. if (exitCode > 0)
  169. ExitProcess (exitCode);
  170. return;
  171. }

三 运行截图

程序开始运行

输入命令和网址

注意下面截图的网址是我和泠在很久以前建的网站地址,目前已经失效了,所以你应该用一个有效的网址替换!

程序得到的网页内容

退出程序

下面是该程序的linux版本,这段程序是《使用C4droid和botbrew在andriod手机上编程 》这篇文章的两个示例程序之一,不过《使用C4droid和botbrew在andriod手机上编程 》这篇文章现在已经放弃维护了!

 /********************************************************************************
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
get-www
main.c Develop Team : ls
Main Programmer : He YiJun (storysnail<at>gmail.com)
License : GPLv3
Last Update : 2013-03-03
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
*********************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> static int gw_connect(char *domain,int port)
{
int sock_sd;
int i;
struct hostent *site_dns;
struct sockaddr_in s_addr;
site_dns = gethostbyname(domain);
if(site_dns == NULL) {
printf("gethostbyname error!\n");
return -;
}
printf("default ip: %s\n",inet_ntoa(*((struct in_addr *)site_dns->h_addr)));
for(i=; i< site_dns->h_length/sizeof(int); i++) {
printf("IP:%d:%s\n",i+,inet_ntoa(*((struct in_addr *)site_dns->h_addr_list[i])));
}
sock_sd = socket(AF_INET,SOCK_STREAM,);
if(sock_sd < ) {
printf ("socket error!");
return -;
}
memset(&s_addr,,sizeof(struct sockaddr_in));
memcpy(&s_addr.sin_addr,site_dns ->h_addr_list[],site_dns->h_length);
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(port);
printf("s_addr ip: %s",inet_ntoa(*((struct in_addr *)&s_addr.sin_addr)));
return (connect(sock_sd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr)) < ? - : sock_sd);
} static int gw_send(int sock_sd,char *fmt,...)
{
char buf [];
va_list argptr;
va_start(argptr,fmt);
vsprintf(buf,fmt,argptr);
va_end(argptr);
printf("Send:\n%s\n",buf);
return send(sock_sd,buf,strlen(buf),);
} void main(int argc,char **argv)
{
int sock_sd;
char rBuf[];
sock_sd = gw_connect("www.7fane.com",);
if(sock_sd < ) {
printf("connect error!\n");
return;
}
//注意:该网站只用于个人测试,在2013年11月末到期,
//如果你在之后的日期使用,请使用其它网页地址
gw_send(sock_sd,"GET http://www.7fane.com/test.html\n");
gw_send(sock_sd,"%c",);
while(read(sock_sd,rBuf,) > )
printf("%c",rBuf[]);
close(sock_sd);
return;
}

使用Code::blocks在windows下写网络程序的更多相关文章

  1. CentOS虚拟机如何设置共享文件夹,并在Windows下映射网络驱动器?

    一.为什么要这么做? 最近在做Linux下的软件开发,但又想使用Windows下的编程工具“Source Insight”. 亲测有效.  要注意查看smb.conf.example,centos7的 ...

  2. [转]CentOS虚拟机如何设置共享文件夹,并在Windows下映射网络驱动器?

    CentOS虚拟机如何设置共享文件夹,并在Windows下映射网络驱动器? 转自这里 一.为什么要这么做? 最近在做Linux下的软件开发,但又想使用Windows下的编程工具“Source Insi ...

  3. windows下写的脚本,在linux下执行失败

    Windows中的换行符为CRLF, 即正则表达式的rn(ASCII码为13和10), 而Unix(或Linux)换行符为LF, 即正则表达式的n. 在Windows和Linux下协同工作的时候, 往 ...

  4. # 如何在Windows下运行Linux程序

    如何在Windows下运行Linux程序 一.搭建 Linux 环境 1.1 安装 VMware Workstation https://www.aliyundrive.com/s/TvuMyFdTs ...

  5. Windows下,通过程序设置全屏抗锯齿(多重采样)的方法

    这里说的全屏抗锯齿,不是基于着色器的FXAA之类的方式,而是兼容性更好的,基于固定管线的多重采样方式. 先来说一下开发环境,我用的是VC2013+GLEW1.11. 要通过程序设置多重采样,首先需要进 ...

  6. [MapReduce_add_1] Windows 下开发 MapReduce 程序部署到集群

    0. 说明  Windows 下开发 MapReduce 程序部署到集群 1. 前提 在本地开发的时候保证 resource 中包含以下配置文件,从集群的配置文件中拷贝 在 resource 中新建  ...

  7. gcc和MinGW的异同(在cygwin/gcc做的东西可以无缝的用在linux下,没有任何问题,是在windows下开发linux程序的一个很好的选择)

    cygwin/gcc和MinGW都是gcc在windows下的编译环境,但是它们有什么区别,在实际工作中如何选择这两种编译器. cygwin/gcc完全可以和在linux下的gcc化做等号,这个可以从 ...

  8. 【Code::Blocks】windows 环境下编译 Code::Blocks(已修正)

    Code::Blocks 在2012-11-25发布了最新的12.11版本,相比上一个版本(10.05),Code::Blocks 进行了许多改进和更新(Change log). 引用 Wikiped ...

  9. 使用code::blocks编译windows的dll链接库

    因为机子上没有安装Visual Studio,所以找到了一种通过code::blocks编译dll的方式,踩到的坑是code::blocks默认的compiler是32位的,这样编译出的dll也是32 ...

随机推荐

  1. [goa]golang微服务框架学习--安装使用

      当项目逐渐变大之后,服务增多,开发人员增加,单纯的使用go来写服务会遇到风格不统一,开发效率上的问题. 之前研究go的微服务架构go-kit最让人头疼的就是定义服务之后,还要写很多重复的框架代码, ...

  2. Trie / Radix Tree / Suffix Tree

    Trie (字典树) "A", "to", "tea", "ted", "ten", "i ...

  3. hdu 5534 (完全背包) Partial Tree

    题目:这里 题意: 感觉并不能表达清楚题意,所以 Problem Description In mathematics, and more specifically in graph theory, ...

  4. 有趣的代码: fixTypeof

    typeof 可以匹配对象的类型,但是他的能力很弱,比如 typeof new String('123')会显示的object这是我们不想看到的结果很久以前JQ的作者通过Object.prototyp ...

  5. 关于 Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() 错误

    最近在做项目的时候发现一个如题的控制台报错. 一看右侧的报错文件是undefined 这下苦恼了,定位不到问题所在. 今天解决了这个问题,就来分享一下. 问题的关键所在是在执行了play()方法以后立 ...

  6. 关于移动端input框 在微信中 和ios中无法输入文字的问题

    这个是一个提交的页面但是总是无法输入进去文字 在uc中是可以的 但是在微信中 或者ios自带浏览器是无法输入的  绞尽脑汁  找了半天  才发现自己多加了一段代码(这个代码是模版中自带的   我靠) ...

  7. adb unknown host service 这个问题的解决,转载

    一直没搞明白这个问题咋出现的,但今天看到一个方法,搞定了!原来是豌豆荚占用了 5037 端口导致. 参见原文章:一个豌豆荚引发的血案——关于ADB server didn't ACK的问题 简单来讲, ...

  8. java 获取服务器 linux 服务器IP 信息

    public String getUnixLocalIp() { String ip = ""; try { Enumeration<?> e1 = (Enumerat ...

  9. 如何选择 H5 游戏引擎

    原生手游市场已是红海,腾讯.网易等寡头独霸天下,H5游戏市场或将成为下一个风口.据笔者所知,很多H5游戏开发团队由于选择引擎不慎导致项目甚至团队夭折.如何选择适合团队和项目的引擎,笔者通过学习和项目实 ...

  10. BZOJ4350: 括号序列再战猪猪侠

    Description 括号序列与猪猪侠又大战了起来. 众所周知,括号序列是一个只有(和)组成的序列,我们称一个括号 序列S合法,当且仅当: 1.( )是一个合法的括号序列. 2.若A是合法的括号序列 ...