function GetLocalIP: String;
const WSVer = $101;
var
wsaData: TWSAData;
P: PHostEnt;
Buf: array [0..127] of Char;
begin
Result := '';
if WSAStartup(MAKEWORD(2,0), wsaData) = 0 then begin
if GetHostName(@Buf, 128) = 0 then begin
P := GetHostByName(@Buf);
if P <> nil then Result := iNet_ntoa(PInAddr(p^.h_addr_list^)^);
end;
WSACleanup;
end;
end;
Pascal to C++
Код:
По идеи она должна возвращать локальный IP. Просто перевожу одну программу из Делфи в С++ Билдер.
Код:
#include <winsock2.h>
#include <iostream>
using namespace std;
/*
function GetLocalIP: String;
const WSVer = $101;
var
wsaData: TWSAData;
P: PHostEnt;
Buf: array [0..127] of Char;
begin
Result := '';
if WSAStartup(MAKEWORD(2,0), wsaData) = 0 then begin
if GetHostName(@Buf, 128) = 0 then begin
P := GetHostByName(@Buf);
if P <> nil then Result := iNet_ntoa(PInAddr(p^.h_addr_list^)^);
end;
WSACleanup;
end;
end;
*/
const char* GetLocalIP() {
const char * result=NULL;
WSAData wsaData;
hostent* P;
char Buf[128];
if ( WSAStartup(MAKEWORD(2,0),&wsaData) == 0 ) {
if ( gethostname(Buf,128) == 0 ) {
P = gethostbyname(Buf);
if ( P != NULL ) {
result = inet_ntoa(*(in_addr*)(*P->h_addr_list));
}
}
WSACleanup();
}
return result;
}
int main () {
cout<<GetLocalIP()<<endl;
return 0;
}
#include <iostream>
using namespace std;
/*
function GetLocalIP: String;
const WSVer = $101;
var
wsaData: TWSAData;
P: PHostEnt;
Buf: array [0..127] of Char;
begin
Result := '';
if WSAStartup(MAKEWORD(2,0), wsaData) = 0 then begin
if GetHostName(@Buf, 128) = 0 then begin
P := GetHostByName(@Buf);
if P <> nil then Result := iNet_ntoa(PInAddr(p^.h_addr_list^)^);
end;
WSACleanup;
end;
end;
*/
const char* GetLocalIP() {
const char * result=NULL;
WSAData wsaData;
hostent* P;
char Buf[128];
if ( WSAStartup(MAKEWORD(2,0),&wsaData) == 0 ) {
if ( gethostname(Buf,128) == 0 ) {
P = gethostbyname(Buf);
if ( P != NULL ) {
result = inet_ntoa(*(in_addr*)(*P->h_addr_list));
}
}
WSACleanup();
}
return result;
}
int main () {
cout<<GetLocalIP()<<endl;
return 0;
}
P.S.: Спасибо за функцию
Код:
getip(){
WSAData wsaData;
PHOSTENT P;
sockaddr_in addr;
char Buf[128];
WSAStartup(MAKEWORD(2,0), &wsaData);
if (gethostname(Buf, 128) == 0){
P = gethostbyname(Buf);
if( P != NULL ){
memcpy(&addr.sin_addr,P->h_addr,P->h_length);
strcpy(Buf,inet_ntoa(addr.sin_addr));
return (AnsiString)Buf;
}
}
return "";
}
WSAData wsaData;
PHOSTENT P;
sockaddr_in addr;
char Buf[128];
WSAStartup(MAKEWORD(2,0), &wsaData);
if (gethostname(Buf, 128) == 0){
P = gethostbyname(Buf);
if( P != NULL ){
memcpy(&addr.sin_addr,P->h_addr,P->h_length);
strcpy(Buf,inet_ntoa(addr.sin_addr));
return (AnsiString)Buf;
}
}
return "";
}