Top.Mail.Ru
Мастера DELPHI, Delphi programming community Титульная страница Поиск, карта сайта Написать письмо 
| Новости | Поиск | FAQ | Статьи | Книги | Новости VCL |
| Форумы ЧАТ | Орешник | KOL и MCK |
Форумы -» Основная («Начинающим»)/ Базы / WinAPI / Компоненты / Сети / Media / Игры / Corba и COM / KOL / FreePascal / .Net / Прочее / RSDN.ORG

« предыдущая ветвь | форум | следующая ветвь »

Вернуть IP адрес подключаемого компа к моему серверу [D5, WinXP]


RomanRom2 ©   (2002-10-29 14:58:00) 

Пишу сервачок, он создает сокет, биндит, слушает.
Когда приходит событие ACCEPT - пишу:

вообще говоря, тут бы узнать, кто (IP адрес) ломится на мою тачку и решать, давать ему акцепт или не давать...

server:=accept(sock,s_addr,s_len);

ну вот, в s_addr по идее должен быть нужный мне адрес...

//------------------------------------------------------------The Windows Sockets accept function accepts a connection on a socket.

SOCKET accept (
SOCKET s,
struct sockaddr FAR* addr,
int FAR* addrlen
);

Parameters
s
[in] A descriptor identifying a socket which is listening for connections after a listen.

addr
[out] An optional pointer to a buffer which receives the address of the connecting entity, as known to the communications layer. The exact format of the addr argument is determined by the address family established when the socket was created.

addrlen
[out] An optional pointer to an integer which contains the length of the address addr.
//------------------------------------------------------------

ну и пишу:
str:=inet_ntoa(s_addr.sin_addr);
memo1.lines.add(TimeToStr(Time)+" ACCEPT "+str);

где на строчке "str:=..." прога вылетает с эксепшеном, когда пытаешься законнектиться с этим сервером, например, телнетом.

//------------------------------------------------------------
Project Project1.exe raised exception class EAccessViolation with message "Acces violation at adress 00445DD6 in module Project1.exe". Read of address 00000004. Process stopped. Use Step ur Run to continue.
//------------------------------------------------------------

ПОЧЕМУ? Какие вообще есть способы выявления IP подключаемой тачки?


Digitman   (2002-10-30 15:38:00) [1]

The Windows Sockets gethostname function returns the standard host name for the local machine.

int gethostname (

char FAR * name,
int namelen
);


Parameters

name

[out] A pointer to a buffer that will receive the host name.

namelen

[in] The length of the buffer.



Remarks

This routine returns the name of the local host into the buffer specified by the name parameter. The host name is returned as a null-terminated string. The form of the host name is dependent on the Windows Sockets provider


ALexe   (2002-10-30 14:55:00) [2]

Парни !!! подскажите как узнать по IP имя локальной машины?


Digitman   (2002-10-30 08:17:00) [3]

>Polevi

Возможно. Не буду возражать. Но все же нелишним будет проверить состояние опции перед стартом слушающего гнезда.

>RomanRom2

> пойдет, еще как пойдет!


Что "пойдет"-то, "чувак" ?)


Polevi   (2002-10-29 18:32:00) [4]

2RomanRom2 © (29.10.02 18:11)
тебе предложили правильный способ, но ты еще к нему не готов


RomanRom2   (2002-10-29 18:11:00) [5]

не, чуваки, что то вы намудрили...
Digitman, пойдет, еще как пойдет! :)))

var
x: u_int;
LocalAddress: TSockAddr;

begin
x:=SizeOf(LocalAddress);
server:=accept(sock,@LocalAddress,@x);

str:=inet_ntoa(LocalAddress.sin_addr);
end;


ВСЕ! :)
Всем спасибо :)


Polevi   (2002-10-29 17:57:00) [6]

PS
я имею в виде что в вин2к все и так работает, без sockopt ^-)


Polevi   (2002-10-29 17:45:00) [7]

2Digitman © (29.10.02 16:53)
надо проверить, я пробовал только на 2k, спасибо за информацию


Digitman   (2002-10-29 16:53:00) [8]

>Polevi

А что, явное setsockopt(SO_CONDITIONAL_ACCEPT = True) в XP не требуется ? Я просто не в курсе, но в Винтукее, как помнится, по-умолчанию SO_CONDITIONAL_ACCEPT = False


Polevi   (2002-10-29 16:38:00) [9]

сам недавно делал такое

const
// WinSock 2 extension -- manifest constants for return values of the condition function
CF_ACCEPT = $0000;
CF_REJECT = $0001;
CF_DEFER = $0002;

type
{ WinSock 2 extension -- WSABUF and QOS struct, include qos.h }
{ to pull in FLOWSPEC and related definitions }

WSABUF = packed record
len: U_LONG; { the length of the buffer }
buf: PChar; { the pointer to the buffer }
end {WSABUF};
PWSABUF = ^WSABUF;
LPWSABUF = PWSABUF;

TServiceType = LongInt;

TFlowSpec = packed record
TokenRate, // In Bytes/sec
TokenBucketSize, // In Bytes
PeakBandwidth, // In Bytes/sec
Latency, // In microseconds
DelayVariation : LongInt;// In microseconds
ServiceType : TServiceType;
MaxSduSize, MinimumPolicedSize : LongInt;// In Bytes
end;
PFlowSpec = ^TFLOWSPEC;

QOS = packed record
SendingFlowspec: TFlowSpec; { the flow spec for data sending }
ReceivingFlowspec: TFlowSpec; { the flow spec for data receiving }
ProviderSpecific: WSABUF; { additional provider specific stuff }
end;
TQualityOfService = QOS;
PQOS = ^QOS;
LPQOS = PQOS;

LPCONDITIONPROC = function (lpCallerId: LPWSABUF; lpCallerData : LPWSABUF; lpSQOS,lpGQOS : LPQOS; lpCalleeId,lpCalleeData : LPWSABUF;
g : DWORD; dwCallbackData : DWORD ) : Integer; stdcall;
function WSAAccept( s: TSocket; addr: PSockAddr; addrlen: PInteger; lpfnCondition : LPCONDITIONPROC; dwCallbackData : DWORD ): TSocket; stdcall;external "ws2_32.dll";

//----------------------------end of winsock2 extension------------------------


function ConditionProc(lpCallerId: LPWSABUF; lpCallerData : LPWSABUF; lpSQOS,lpGQOS : LPQOS; lpCalleeId,lpCalleeData : LPWSABUF;
g : DWORD; dwCallbackData : DWORD ) : Integer;stdcall;
var
interfaceIP,clientIP:string;
port:WORD;
begin
clientIP:=inet_ntoa(PSockAddrIn(lpCallerId.buf).sin_addr);
interfaceIP:=inet_ntoa(PSockAddrIn(lpCalleeId.buf).sin_addr);
port:=htons(PSockAddrIn(lpCalleeId.buf).sin_port);
Result:=CF_ACCEPT;
if НЕХОЧУ!!! then
begin
Result:=CF_REJECT;
Writeln(Format("Reject client with IP %s, requested interface %s:%d",[clientIP,interfaceIP,port]));
end
end;

//вызов
FSocket:=WSAAccept(AListenClient.FSocket, @FAddr, @Len, @ConditionProc,0)


Digitman   (2002-10-29 15:07:00) [10]


> кто (IP адрес) ломится на мою тачку и решать, давать ему
> акцепт или не давать...



accept() дла этого не пойдет.

см. WSAAccept()


Наверх

Титульная страница Поиск, карта сайта Написать письмо