⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 unit1.~cp

📁 获取本机ip地址的3种方法。CB4.0编译
💻 ~CP
字号:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void  TForm1::GetHostIpAddress()  //获得IP地址
{  
struct  hostent  *thisHost;  
struct  in_addr  in;  
char  MyName[80];  
char  *hostname,*ptr;  

WORD  wVersionRequested;  
WSADATA  wsaData;  
int  err;  
wVersionRequested  =  MAKEWORD(  2,  0  );
err  =  WSAStartup(  wVersionRequested,  &wsaData  );  
if(  err  !=  0  )  
     return;  


if(LOBYTE(  wsaData.wVersion  )  !=  2    &&  
       HIBYTE(  wsaData.wVersion  )  !=  0  )
     {  
       WSACleanup(  );  
       return;  
   }  

if(gethostname(MyName,80)==SOCKET_ERROR)  
     return;  

if(!(thisHost=gethostbyname(MyName)))  
     return;  
memset((void  *)&in,sizeof(in),0);  
hostname=thisHost->h_name;  
in.s_addr=*((unsigned  long  *)thisHost->h_addr_list[0]);  
if(!(ptr=inet_ntoa(in)))  
     return;  
WSACleanup(  );  
Edit1->Text=AnsiString(ptr);  
Edit2->Text=AnsiString(hostname);  
}  
//---------------------------------------------------------------------------  



void __fastcall TForm1::Button1Click(TObject *Sender)
{
         Label1->Caption = "IP: " + Powersock1->LocalIP;
//         if (Powersock1->LocalIP == "0.0.0.0")
//             ShowMessage("not connected");
//         else
//             ShowMessage(Powersock1->LocalIP);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button2Click(TObject *Sender)
{
GetHostIpAddress();        
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button3Click(TObject *Sender)
{
                     hostent  *p;
                     char  s[128];  
                     char  *p2;  
      
           //Get  the  computer  name  
                   gethostname(s,  128);  
                   p  =  gethostbyname(s);  
                   Memo1->Lines->Add(p->h_name);    

           //Get  the  IpAddress  
                   p2  =  inet_ntoa(*((in_addr  *)p->h_addr));  
                   Memo1->Lines->Add(p2);  
}
//---------------------------------------------------------------------------

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -