请高手帮我解释一下这段C++代码

2024-11-05 22:01:07
推荐回答(2个)
回答1:

这是一个基于对话框的网络通信编程入门实例

回答2:

void list_interfaces (HWND hwnd)
{
LPHOSTENT h; //主机信息结构
char name [128];
long r;
char *add, **list;
int index;
WSADATA wd;

r = WSAStartup (0x0002, &wd); //初始化winsock,版本写得好像有点问题应该是0x0202或者0x2000
if (!r)
{
r = gethostname (name, 128); //获取本机(计算机)名比如: DEMON-PC(我的计算机名)
if (!r)
{
h = gethostbyname (name); //通过本机名获取本机信息,比如IP地址信息
if (h)
{
if (h -> h_addrtype == AF_INET)//判断本机协议类型AF_INET表是IPV4,
{
list = h->h_addr_list; //h_add_list[0]表示第一个IP地址的起始地址
add = *list; //add存储IP地址的起始指针
my_addr = *((DWORD*)add);
sprintf(name, "%u.%u.%u.%u", (unsigned)(unsigned char)add[0], (unsigned)(unsigned char)add[1], (unsigned)(unsigned char)add[2], (unsigned)(unsigned char)add[3]);
//name格式成IP串
strcpy(my_addr_txt, name);
while (*list)
{//遍历各个IP地址(如果有多个IP的话)
add = *list;
sprintf(name, "%u.%u.%u.%u", (unsigned)(unsigned char)add[0], (unsigned)(unsigned char)add[1], (unsigned)(unsigned char)add[2], (unsigned)(unsigned char)add

[3]);
index = SendDlgItemMessage(hwnd, IDC_INTERFACE, LB_ADDSTRING, 0, (LPARAM)name);//向IDC_INTERFACE控件发送IP地址信息的消息
SendDlgItemMessage(hwnd, IDC_INTERFACE, LB_SETITEMDATA, index, (LPARAM)*((DWORD*)add));//设置IDC_INTERFACE的字串信息
list++;
}
SendDlgItemMessage(hwnd, IDC_INTERFACE, LB_SETCURSEL, 0, 0);
if (SendDlgItemMessage(hwnd, IDC_INTERFACE, LB_GETITEMDATA, 0, 0) != 0x0100007F)//如果是本机作息,做如下设置
{
strcpy(name, "127.0.0.1");//这个是本地址
index = SendDlgItemMessage(hwnd, IDC_INTERFACE, LB_ADDSTRING, 0, (LPARAM)name);
SendDlgItemMessage(hwnd, IDC_INTERFACE, LB_SETITEMDATA, index, (LPARAM)0x0100007F);
}

}
}
}
}
WSACleanup();//释放winsock库
}

注:这段代码有点问题做本机处理的时候,没必要这么麻烦~