使用Code::blocks在windows下写网络程序
作者 | HeYiJun – storysnailgmail.com | ||||
团队 | ls | ||||
版权 | 转载请保留本声明! 本文档包含的原创代码根据GeneralPublic License,v3 发布 本文档根据GNUFree Documentation License 1.3发布 文中所引用的软件版权详见各软件版权具体声明,文中所提及的所有商标均为各自商标所有人的财产。 | ||||
更新 |
|
前言:
这是一个用来读取指定网页内容的程序。当前还非常原始,但已经能完成基本的功能。未来我会在这个程序的基础上不断扩充,让这个程序变成一个可用的更新检测程序!
一:windows下用Code::blocks开发网络程序
1:
Code::blocks 中新建一个工程
2:
建完工程后点击Project菜单,选择Buildoptions...
3:
选择Linkersettings标签页,在Otherlinker options:中添加:
-lwsock32
二 源代码
点击(此处)折叠或打开
- /***********************************************************************
- * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
- Eabc-version-verfy.c
- Develop Team : ls
- Team Leader : He YiJun (storysnail<at>gmail.com)
- Main Programmer : He YiJun
- Programmer : Ling Ying
- Program comments : Ling Ying
- Dict Editor : Yang QiuXi
- Documents : Ling Ying、 Yang QiuXi
- Art Designer : He YiJun
- License : GPLv3
- Last Update : 2013-02-25
- * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
- *************************************************************************/
- #include <windows.h> // 新增 windows.h
- #include <winsock2.h>
- //#pragma comment(lib, "ws2_32.lib") // For VS
- #include <tchar.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <malloc.h>
- #include <io.h>
- #ifdef _MT
- #include <process.h>
- #endif
- /* DWORD_PTR (pointer precision unsigned integer) is used for integers
- * that are converted to handles or pointers
- * This eliminates Win64 warnings regarding conversion between
- * 32 and 64-bit data, as HANDLEs and pointers are 64 bits in
- * Win64 (See Chapter 16). This is enable only if _Wp64 is defined.
- */
- #if !defined(_Wp64)
- #define DWORD_PTR DWORD
- #define LONG_PTR LONG
- #define INT_PTR INT
- #endif
- #define MAX_RQRS_LEN 0x1000 //4096
- /* Required for sockets */
- #define SERVER_PORT 80
- typedef struct {
- LONG32 rsLen;
- BYTE record [MAX_RQRS_LEN];
- } RESPONSE;
- typedef struct {
- LONG32 rqLen;
- BYTE record [MAX_RQRS_LEN];
- } REQUEST;
- #define RQ_SIZE sizeof (REQUEST)
- #define RQ_HEADER_LEN RQ_SIZE-MAX_RQRS_LEN
- #define RS_SIZE sizeof (RESPONSE)
- #define RS_HEADER_LEN RS_SIZE-MAX_RQRS_LEN
- static BOOL SendRequest (REQUEST *, SOCKET);
- static BOOL ReceiveResponse (RESPONSE *, SOCKET);
- static VOID PrintError (LPCTSTR , DWORD , BOOL);
- struct sockaddr_in clientSAddr;
- int _tmain (int argc, LPSTR argv[])
- {
- SOCKET clientSock = INVALID_SOCKET;
- REQUEST request;
- RESPONSE response;
- WSADATA WSStartData; /* Socket library data structure */
- DWORD conVal;
- while (1) {
- _tprintf (_T("%s"), _T("\nEnter Command: "));
- _fgetts ((char *)request.record, MAX_RQRS_LEN-1, stdin);
- /* Get rid of the new line at the end */
- /* Messages use 8-bit characters */
- request.record[strlen((char *)request.record)-1] = '\0';
- if (strcmp ((char *)request.record, "$Quit") == 0)
- break;
- if (strncmp ((char *)request.record, "GET",3) == 0)
- request.record[strlen((char *)request.record)] = '\n';
- /* Initialize the WS library. Ver 2.2 */
- if (WSAStartup (MAKEWORD (2, 2), &WSStartData) != 0)
- PrintError (_T("Cannot support sockets"), 1, TRUE);
- /* Connect to the server */
- /* Follow the standard client socket/connect sequence */
- clientSock = socket(AF_INET, SOCK_STREAM, 0);
- if (clientSock == INVALID_SOCKET)
- PrintError (_T("Failed client socket() call"), 2, TRUE);
- memset (&clientSAddr, 0, sizeof(clientSAddr));
- clientSAddr.sin_family = AF_INET;
- //clientSAddr.sin_addr.s_addr = htonl(inet_addr ("121.127.248.96"));
- clientSAddr.sin_addr.s_addr = inet_addr ("121.127.248.96");
- clientSAddr.sin_port = htons(SERVER_PORT);
- conVal = connect (clientSock, (struct sockaddr *)&clientSAddr, sizeof(clientSAddr));
- if (conVal == SOCKET_ERROR) PrintError (_T("Failed client connect() call)"), 3, TRUE);
- SendRequest (&request, clientSock);
- ReceiveResponse (&response, clientSock);
- shutdown (clientSock, SD_BOTH); /* Disallow sends and receives */
- closesocket (clientSock);
- WSACleanup();
- close (clientSock);
- }
- _tprintf (_T("\n****Leaving client\n"));
- return 0;
- }
- // GET http://www.7fane.com/test.html
- BOOL SendRequest (REQUEST *pRequest, SOCKET sd)
- {
- /* Send the the request to the server on socket sd */
- BOOL disconnect = FALSE;
- LONG32 nRemainSend, nXfer;
- LPBYTE pBuffer;
- //char target[]="GET http://www.7fane.com/test.html\n";
- pRequest->rqLen = (DWORD)(strlen ((char *)pRequest->record) + 1);
- nRemainSend = pRequest->rqLen;
- pBuffer = (LPBYTE)pRequest->record;
- _tprintf (_T("%s%s"), _T("\nNow SendRequestMessage: "),pBuffer);
- while (nRemainSend > 0 && !disconnect) {
- nXfer = send (sd, (char *)pBuffer, nRemainSend, 0);
- //nXfer = send (sd, target, strlen(target), 0);
- if (nXfer == SOCKET_ERROR) PrintError (_T("client send() failed"), 5, TRUE);
- disconnect = (nXfer == 0);
- nRemainSend -=nXfer;
- pBuffer += nXfer;
- _tprintf (_T("%s%d"), _T("\nSend btyes: "),nXfer);
- //_tprintf (_T("%s%s"), _T("\nSend content: "),target);
- _tprintf (_T("%s%s"), _T("\nSend content: "),pRequest->record);
- }
- return disconnect;
- }
- BOOL ReceiveResponse (RESPONSE *pResponse, SOCKET sd)
- {
- BOOL disconnect = FALSE;
- LONG32 nRemainRecv, nXfer;
- LPBYTE pBuffer;
- _tprintf (_T("%s"), _T("\nNow ReceiveResponseMessage! "));
- while(!disconnect) {
- /* Read each response and send it to std out.*/
- memset (pResponse->record, 0, MAX_RQRS_LEN);
- nRemainRecv = MAX_RQRS_LEN;
- pBuffer = (LPBYTE)pResponse->record;
- while (nRemainRecv > 0 && !disconnect) {
- nXfer = recv (sd, (char *)pBuffer, nRemainRecv, 0);
- if (nXfer == SOCKET_ERROR) PrintError (_T("client response recv() failed"), 7, TRUE);
- disconnect = (nXfer == 0);
- nRemainRecv -=nXfer;
- pBuffer += nXfer;
- if(!disconnect) {
- _tprintf (_T("%s[%d]"), _T("\nReceive bytes: "),nXfer);
- _tprintf (_T("%s\n%s"), _T("\nReceive content: "),pResponse->record);
- }
- }
- }
- return disconnect;
- }
- VOID PrintError (LPCTSTR userMessage, DWORD exitCode, BOOL printErrorMessage)
- {
- DWORD eMsgLen, errNum = GetLastError ();
- LPTSTR lpvSysMsg;
- _ftprintf (stderr, _T("%s\n"), userMessage);
- if (printErrorMessage) {
- eMsgLen = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL, errNum, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPTSTR) &lpvSysMsg, 0, NULL);
- if (eMsgLen > 0)
- {
- _ftprintf (stderr, _T("%s\n"), lpvSysMsg);
- }
- else
- {
- _ftprintf (stderr, _T("Last Error Number; %d.\n"), (int)errNum);
- }
- if (lpvSysMsg != NULL) LocalFree (lpvSysMsg); /* Explained in Chapter 5. */
- }
- if (exitCode > 0)
- ExitProcess (exitCode);
- return;
- }
三 运行截图
程序开始运行
输入命令和网址
注意下面截图的网址是我和泠在很久以前建的网站地址,目前已经失效了,所以你应该用一个有效的网址替换!
程序得到的网页内容
退出程序
下面是该程序的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 -2;
- }
- printf("default ip: %s\n",inet_ntoa(*((struct in_addr *)site_dns->h_addr)));
- for(i=0; i< site_dns->h_length/sizeof(int); i++) {
- printf("IP:%d:%s\n",i+1,inet_ntoa(*((struct in_addr *)site_dns->h_addr_list[i])));
- }
- sock_sd = socket(AF_INET,SOCK_STREAM,0);
- if(sock_sd < 0) {
- printf ("socket error!");
- return -1;
- }
- memset(&s_addr,0,sizeof(struct sockaddr_in));
- memcpy(&s_addr.sin_addr,site_dns ->h_addr_list[0],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)) < 0 ? -1 : sock_sd);
- }
- static int gw_send(int sock_sd,char *fmt,...)
- {
- char buf [1024];
- 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),0);
- }
- void main(int argc,char **argv)
- {
- int sock_sd;
- char rBuf[3];
- sock_sd = gw_connect("www.7fane.com",80);
- if(sock_sd < 0) {
- printf("connect error!\n");
- return;
- }
- //注意:该网站只用于个人测试,在2013年11月末到期,
- //如果你在之后的日期使用,请使用其它网页地址
- gw_send(sock_sd,"GET http://www.7fane.com/test.html\n");
- gw_send(sock_sd,"%c",10);
- while(read(sock_sd,rBuf,1) > 0)
- printf("%c",rBuf[0]);
- close(sock_sd);
- return;
- }