局域网网络编程

 

局域网网络编程

 

一、获取网络邻居

列出局域网内同一网关下的所有计算机名和所在的工作组。Windows提供了一套专用的Windows的网络编程函数集。下面介绍下比较常用的函数:

l        WNetOpenEnum:开始枚举网络资源或者存在的连接。

DWORD WNetOpenEnum(

  DWORD dwScope, //枚举范围

  DWORD dwType, //列举的资源类型

  DWORD dwUsage, //获取可用的资源

  LPNETRESOURCE lpNetResource, //资源结构

  LPHANDLE lphEnum ); //枚举的句柄

dwScope

RESOURCE_CONNECTED

All currently connected resources (the dwUsage parameter is ignored).

RESOURCE_GLOBALNET

All resources on the network.

RESOURCE_REMEMBERED

All remembered (persistent) connections (the dwUsage parameter is ignored). These connections may or may not currently be connected.

dwType:

RESOURCETYPE_ANY

All resources (this value cannot be combined with RESOURCETYPE_DISK or RESOURCETYPE_PRINT).

RESOURCETYPE_DISK

All disk resources.

RESOURCETYPE_PRINT

All print resources.

dwUsage:

0

All resources.

RESOURCEUSAGE_CONNECTABLE

All connectable resources.

RESOURCEUSAGE_CONTAINER

All container resources.

 

lpNetResource:NETRESOURCE结构的一个指针,如果参数dwScope不等于RESOURCE_GLOBALNET,那么这个值必须为NULL。

 

l        WNetEnumResource:WNetEnumResource枚举一个WNetOpenEnum的网络资源。

DWORD WNetEnumResource(

  HANDLE hEnum, /枚举句柄

  LPDWORD lpcCount, // 资源节点列表

  LPVOID lpBuffer, //buffer,NETRESOURCE的数组

  LPDWORD lpBufferSize ); //buffer大小

这里都比较常用的结构体是NETRESOURCE,定义如下:

typedef struct _NETRESOURCE {

  DWORD dwScope; //同前

  DWORD dwType; //同前

  DWORD dwDisplayType; //如何显示这个网络实体

  DWORD dwUsage;

  LPTSTR lpLocalName; //本地名字

  LPTSTR lpRemoteName; //网络资源,远端网络的名字

  LPTSTR lpComment; //注释字符串指针

  LPTSTR lpProvider; //网络提供者的名字指针

} NETRESOURCE

;

dwDisplayType:

RESOURCEDISPLAYTYPE_DOMAIN

The object should be displayed as a domain.

RESOURCEDISPLAYTYPE_GENERIC

The method used to display the object does not matter.

RESOURCEDISPLAYTYPE_SERVER

The object should be displayed as a server.

RESOURCEDISPLAYTYPE_SHARE

The object should be displayed as a share.

 

枚举网络邻居程序:

BOOL Enumerate(LPNETRESOURCE lpNetRC_p,int depth)

{

    HANDLE hEnum = 0;

    DWORD dwResult = WNetOpenEnum(RESOURCE_GLOBALNET,RESOURCETYPE_ANY

         ,0,lpNetRC_p,&hEnum);

    if(dwResult != NO_ERROR)

         return FALSE;

    LPNETRESOURCE lpnrLocal = 0;

    DWORD dwEntries = -1;

    DWORD dwBuffer = 16384;

    do

    {

         lpnrLocal = (LPNETRESOURCE)GlobalAlloc(GPTR,dwBuffer);

         dwResult = WNetEnumResource(hEnum,&dwEntries,lpnrLocal,&dwBuffer);

         if(dwResult  == NO_ERROR)

         {

             for (DWORD i=0;i<dwEntries;i++)

             {

                  CString name;

                  name = (CString)lpnrLocal[i].lpRemoteName;

                  name += _T(" ");

                  name += lpnrLocal[i].lpLocalName;

                  name += _T(" ");

                  name += lpnrLocal[i].lpComment;

                  CListBox* pList = (CListBox*)GetDlgItem(IDC_LIST);

                  if(depth == 1)

                      pList->AddString(name);

                  if (depth == 2)

                  {

                      pList->AddString(_T(" ")+name);

                      m_Neighborlist.AddTail(name);

                  }

                  CString str;

                  str.Format(_T("%d"),depth);

                  m_list.AddTail(name + str);

if(RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER))

                  {  

                      if(!Enumerate(&lpnrLocal[i],depth+1))

                      {

 

                      }

                  }

             }

         }

         else

         {

             if(dwResult != ERROR_NO_MORE_ITEMS)

             {

                  return FALSE;

             }

         }

    } while (dwResult != ERROR_NO_MORE_ITEMS);

    if(lpnrLocal)

         GlobalFree((HGLOBAL)lpnrLocal);

    WNetCloseEnum(hEnum);

    return TRUE;

}

 

二、IP地址和主机名之间的转换

       在前面已经介绍过几个函数来获取IP地址和主机信息,分别是gethostname,gethostbyname,gethostbyaddr几个函数,其中gethostname获取主机名,gethostbyname实现主机名到ip地址的转换,gethostbyaddr实现ip地址到主机的转换。                                                                                                                                                                                                                                                                                    

       下面介绍几个数据结构:

struct in_addr {

  union {

    struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;//4个char

    struct { u_short s_w1,s_w2; } S_un_w;//2个short

  u_long S_addr;//1个long

  } S_un;

};

可以用函数inet_ntoa来将一个地址变成标准的点地址:

char FAR* inet_ntoa( struct in_addr in );

This function converts an (Ipv4) Internet network address into a string in Internet standard dotted format.

 

addrinfo描述了地址的相关信息:

struct addrinfo {

  int ai_flags; //标识

  int ai_family;//协议族

  int ai_socktype; //socke类型

  int ai_protocol; //协议,0

  size_t ai_addrlen; //长度

  char* ai_canonname; //主机规范的名字

  struct sockaddr* ai_addr; //sockaddr结构的指针

  struct addrinfo* ai_next; //下一个

};

 

//根据主机获取ip地址列表

int GetIpAddress(const CString &sHostName, CStringArray &sIpAddress)//获得本地IP

{

    struct hostent FAR * lpHostEnt=gethostbyname(sHostName);

    sIpAddress.RemoveAll();

    if(lpHostEnt==NULL)

    {

         //产生错误

         return GetLastError();

    }

    //获取IP

    int i=0;

    LPSTR lpAddr=lpHostEnt->h_addr_list[i];

    CString temp;

    while(lpAddr)

    {

         i++;

         struct in_addr inAddr;

         memmove(&inAddr,lpAddr,4);

         //转换为标准格式

         temp=inet_ntoa(inAddr);

         if(temp.IsEmpty())

         {

             break;

         }

         sIpAddress.Add(temp);

         lpAddr=lpHostEnt->h_addr_list[i];

    }

    return 0;

}

 

三、映射网络驱动器

       将邻近的计算机的文件资源看成时本地的一个驱动器,是网络驱动器映射的核心思想。只要利用几个函数就可以实现映射网络驱动器。

       WNetAddConnection2:这个函数将与一个网络资源进行连接,然后将网络资源重定向到一个本地设备。

DWORD WNetAddConnection2(

  LPNETRESOURCE lpNetResource, //连接细节

  LPCTSTR lpPassword,//共享资源密码

  LPCTSTR lpUsername, //共享资源用户名

  DWORD dwFlags); //连接可选项

The WNetAddConnection2 function makes a connection to a network resource. The function can redirect a local device to the network resource.

对lpNetResource参数的一些说明:

dwType

Specifies the type of network resource to connect to.

If the lpLocalName member points to a nonempty string, this member can be equal to RESOURCETYPE_DISK or RESOURCETYPE_PRINT.

If lpLocalName is NULL, or if it points to an empty string, dwType can be equal to RESOURCETYPE_DISK, RESOURCETYPE_PRINT, or RESOURCETYPE_ANY.

Although this member is required, its information may be ignored by the network service provider.

lpLocalName

Points to a null-terminated string that specifies the name of a local device to redirect, such as "F:" or "LPT1". The string is treated in a case-insensitive manner.

If the string is empty, or if lpLocalName is NULL, the function makes a connection to the network resource without redirecting a local device.

lpRemoteName

Points to a null-terminated string that specifies the network resource to connect to. The string can be up to MAX_PATH characters in length, and must follow the network provider's naming conventions.

lpProvider

Points to a null-terminated string that specifies the network provider to connect to.

If lpProvider is NULL, or if it points to an empty string, the operating system attempts to determine the correct provider by parsing the string pointed to by the lpRemoteName member.

If this member is not NULL, the operating system attempts to make a connection only to the named network provider.

You should set this member only if you know the network provider you want to use. Otherwise, let the operating system determine which provider the network name maps to.

dwFlags:

CONNECT_INTERACTIVE

If this flag is set, the operating system may interact with the user for authentication purposes.

CONNECT_PROMPT

This flag instructs the system not to use any default settings for user names or passwords without offering the user the opportunity to supply an alternative. This flag is ignored unless CONNECT_INTERACTIVE is also set.

CONNECT_REDIRECT

This flag forces the redirection of a local device when making the connection.

If the lpLocalName member of NETRESOURCE specifies a local device to redirect, this flag has no effect, because the operating system still attempts to redirect the specified device. When the operating system automatically chooses a local device, the dwType member must not be equal to RESOURCETYPE_ANY.

If this flag is not set, a local device is automatically chosen for redirection only if the network requires a local device to be redirected.

Windows Server 2003 and Windows XP:  When the system automatically assigns network drive letters, letters are assigned beginning with Z:, then Y:, and ending with C:. This reduces collision between per-logon drive letters (such as network drive letters) and global drive letters (such as disk drives). Note that previous releases assigned drive letters beginning with C: and ending with Z:.

CONNECT_UPDATE_PROFILE

The network resource connection should be remembered.

If this bit flag is set, the operating system automatically attempts to restore the connection when the user logs on.

The operating system remembers only successful connections that redirect local devices. It does not remember connections that are unsuccessful or deviceless connections. (A deviceless connection occurs when the lpLocalName member is NULL or points to an empty string.)

If this bit flag is clear, the operating system does not automatically restore the connection at logon.

CONNECT_COMMANDLINE

If this flag is set, the operating system prompts the user for authentication using the command line instead of a graphical user interface (GUI). This flag is ignored unless CONNECT_INTERACTIVE is also set.

Windows 2000/NT and Windows Me/98/95:  This value is not supported.

CONNECT_CMD_SAVECRED

If this flag is set, and the operating system prompts for a credential, the credential should be saved by the credential manager. If the credential manager is disabled for the caller's logon session, or if the network provider does not support saving credentials, this flag is ignored. This flag is also ignored unless you set the CONNECT_COMMANDLINE flag.

Windows 2000/NT and Windows Me/98/95:  This value is not supported.

 

//映射网络驱动器

void edirect(const char *LocalName,const char *RemoteName,const char * UserName,const char *Password)

{

    NETRESOURCE nr;

    DWORD res;

    char szUserName[32],

         szPassword[32],

         szLocalName[32],

         szRemoteName[MAX_PATH];

 

    strcpy(szUserName,UserName);

    strcpy(szPassword,Password);

    strcpy(szLocalName,LocalName);

    strcpy(szRemoteName,RemoteName);

   

    nr.dwType = RESOURCETYPE_ANY;

    nr.lpLocalName = szLocalName;

    nr.lpRemoteName = szRemoteName;

    nr.lpProvider = NULL;

    //

    res = WNetAddConnection2(&nr, szPassword, szUserName, FALSE);

    //

    switch(res)

    {

    case NO_ERROR:

         AfxMessageBox("网络驱动器映射成功");

         break;

    case ERROR_BAD_PROFILE:

         AfxMessageBox("ERROR_BAD_PROFILE");

         break;

    case ERROR_CANNOT_OPEN_PROFILE:

         AfxMessageBox("ERROR_CANNOT_OPEN_PROFILE");

         break;

    case ERROR_DEVICE_IN_USE:

         AfxMessageBox("ERROR_DEVICE_IN_USE");

         break;

    case ERROR_EXTENDED_ERROR:

         AfxMessageBox("ERROR_EXTENDED_ERROR");

         break;

    case ERROR_NOT_CONNECTED:

         AfxMessageBox("ERROR_NOT_CONNECTED");

         break;

    case ERROR_OPEN_FILES:

         AfxMessageBox("ERROR_OPEN_FILES");

         break;

    default:

         AfxMessageBox("未知错误,可能需要帐号和密码认证,或者该主机或文件不存在");

         break;

    }

    return;

}

 

四、获取局域网内其他计算机的信息

       使用命令Nbtstat:显示协议同届和当前TCP/IP连接。Nbtstat的参数为:

-a   (适配器状态)    列出指定名称的远程机器的名称表

 -A   (适配器状态)    列出指定 IP 地址的远程机器的名称表。

 -c   (缓存)          列出远程[计算机]名称及其 IP 地址的 NBT 缓存

 -n   (名称)          列出本地 NetBIOS 名称。

 -r   (已解析)        列出通过广播和经由 WINS 解析的名称

 -R   (重新加载)      清除和重新加载远程缓存名称表

 -S   (会话)          列出具有目标 IP 地址的会话表

 -s   (会话)          列出将目标 IP 地址转换成计算机 NETBIOS 名称的会话表。

 -RR  (释放刷新)      将名称释放包发送到 WINS,然后启动刷新

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值