获取网络协议的步骤和代码(1)(3)
四、添加代码
五、添加对象/库模块
1、 于“GetNetProtocolsDlg.cpp”文件内添加包含语句
- #include "stdafx.h"
- #include "GetNetProtocols.h"
- #include "GetNetProtocolsDlg.h"
- #include <winsock2.h>
2、添加获取网络协议的函数代码
- void CGetNetProtocolsDlg::OnGetnetprotocols()
- {
- // TODO: Add your control notification handler code here
- WSADATA WSAData;
- int i, nRet;
- DWORD dwErr;
- WSAPROTOCOL_INFO *lpProtocolBuf = NULL;
- DWORD dwBufLen = 0;
- CString strTemp;
- if (WSAStartup(MAKEWORD(2,2), &WSAData))
- {
- strTemp.Format("WSAStartup %d", WSAGetLastError());
- m_ListProtocols.AddString(strTemp);
- }
- else//第一层
- {
- //方法:WSAEnumProtocols获得计算机安装的协议
- // First, have WSAEnumProtocols tell you how big a buffer you need.
- nRet = WSAEnumProtocols(NULL, lpProtocolBuf, &dwBufLen);
- if (SOCKET_ERROR != nRet)
- {
- strTemp.Format("WSAEnumProtocols: should not have succeeded\r\n");
- m_ListProtocols.AddString(strTemp);
- }
- else if (WSAENOBUFS != (dwErr = WSAGetLastError()))
- {
- // WSAEnumProtocols failed for some reason not relating to buffer size - also odd.
- strTemp.Format("WSAEnumProtocols(1): %d\r\n", WSAGetLastError());
- m_ListProtocols.AddString(strTemp);
- }
- else//第二层
- {
- // WSAEnumProtocols failed for the "expected" reason.
- // Now you need to allocate a buffer that is the right size.
- lpProtocolBuf = (WSAPROTOCOL_INFO *)malloc(dwBufLen);
- if (lpProtocolBuf)
- {
- // Now you can call WSAEnumProtocols again with the
- // expectation that it will succeed
- // because you have allocated a big enough buffer.
- nRet = WSAEnumProtocols(NULL, lpProtocolBuf, &dwBufLen);
- if (SOCKET_ERROR == nRet)
- {
- strTemp.Format("WSAEnumProtocols(3): %d\r\n", WSAGetLastError());
- m_ListProtocols.AddString(strTemp);
- }
- else
- {
- // Enumerate the protocols.
- strTemp.Format("该计算机安装的网络协议有:");
- m_ListProtocols.AddString(strTemp);
- for (i=0; i<nRet; i++)
- {
- strTemp.Format(" 协议%d:<%s>\r",i+1, lpProtocolBuf[i].szProtocol);
- m_ListProtocols.AddString(strTemp);
- }
- }
- free(lpProtocolBuf);
- }//if (lpProtocolBuf)结束
- }//第二层else结束
- }//第一层else结束
- //调用WSACleanup函数进行WinSock的清理工作,以便释放其占用的资源
- WSACleanup();
- }
点“工程”,点“设置”,点选“连接”,添加“Ws2_32.lib ”模块。
六、编译
七、运行
评论暂时关闭