Sign in to follow this  
Followers 0
woleium

Determine clinet IP from TCP connection

3 posts in this topic

#1 ·  Posted (edited)

Hello everyone!

I can't work out how to determine the connecting client IP when using the TCPStartup() function

I'd like to limit connections based on IP, so if someone connects with the wrong IP the session is disconnected.

Any ideas?

Edited by woleium

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Have you tried searching the forum?

I'm fairly sure I've seen a function that does what you want somewhere in here.

Edit:

Here you go:

Func _TCPSocketToIP(ByRef $ivOSocket)
    Local $stvSockAddr = DllStructCreate("short;ushort;ptr;char[8]")
    Local $avResult = DllCall("Ws2_32.dll", "int", "getpeername", "int", $ivOSocket, "ptr", DllStructGetPtr($stvSockAddr), "ptr*", DllStructGetSize($stvSockAddr))
    If Not IsArray($avResult) Or (IsArray($avResult) And $avResult[0]) Then Return(SetError(1, 0, 0)); Something went wrong
    $avResult = DllCall("Ws2_32.dll", "str*", "inet_ntoa", "ptr", DllStructGetData($stvSockAddr, 3))
    If Not IsArray($avResult) Or (IsArray($avResult) And Not $avResult[0]) Then Return(SetError(2, 0, 0)); Something else went wrong
    Return $avResult[0]
EndFunc

An example of how to use it:

TCPStartup()

Dim $ioSocket = TCPConnect(TCPNameToIP("www.google.com"), 80)
If $ioSocket = -1 Then Exit; Could not open socket

ConsoleWrite(_TCPSocketToIP($ioSocket) & @LF)

TCPCloseSocket($ioSocket)
TCPShutdown()

Func _TCPSocketToIP(ByRef $ivOSocket)
    Local $stvSockAddr = DllStructCreate("short;ushort;ptr;char[8]")
    Local $avResult = DllCall("Ws2_32.dll", "int", "getpeername", "int", $ivOSocket, "ptr", DllStructGetPtr($stvSockAddr), "ptr*", DllStructGetSize($stvSockAddr))
    If Not IsArray($avResult) Or (IsArray($avResult) And $avResult[0]) Then Return(SetError(1, 0, 0)); Something went wrong
    $avResult = DllCall("Ws2_32.dll", "str*", "inet_ntoa", "ptr", DllStructGetData($stvSockAddr, 3))
    If Not IsArray($avResult) Or (IsArray($avResult) And Not $avResult[0]) Then Return(SetError(2, 0, 0)); Something else went wrong
    Return $avResult[0]
EndFunc
Edited by FreeFry

Share this post


Link to post
Share on other sites

Have you tried searching the forum?

I'm fairly sure I've seen a function that does what you want somewhere in here.

Yep, I looked for ages... I must have been searching for the wrong thing. Thank you very much :-)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0