Jump to content
Sign in to follow this  
Info

An 8 lines function in AutoIt to C++

Recommended Posts

Info

Func _SocketGetIP($Data)
    Local $Struct, $Return
    $Struct = DllStructCreate('short;ushort;uint;char[8]')
    $Return = DllCall('Ws2_32.dll', 'int', 'getpeername', 'int', $Data, 'ptr', DllStructGetPtr($Struct), 'int*', DllStructGetSize($Struct))
    If @error Or $Return[0] <> 0 Then Return 0
    $Return = DllCall('Ws2_32.dll', 'str', 'inet_ntoa', 'int', DllStructGetData($Struct, 3))
    If @error Then Return 0
    $Struct = 0
    Return $Return[0]
EndFunc   ;==>_SocketGetIP

Here's my attempt

bool GetSocketIP(const SOCKET &socket, char *sBuffer)
{
    sockaddr sa;
    ZeroMemory(&sa, sizeof sa);
    int iLen = sizeof sa;

    if( getpeername(socket, &sa, &iLen) != 0 )
        return false;

    strcpy(sBuffer, inet_ntoa(reinterpret_cast<sockaddr_in*>(&sa)->sin_addr));

    return true;
}

Thanks

Edit: Forgot to say, the C++ functions isn't really like the AutoIt one because of the return values and the parameters and stuff, but you get the idea.

Edited by Info

Share this post


Link to post
Share on other sites
Info

Hehe nvm, got it to work.

bool tcp_server::GetSocketIP(const SOCKET &socket, char *sBuffer)//might only work for ipv4, don't know why
{
    sockaddr sa;
    ZeroMemory(&sa, sizeof sa);
    int iLen = sizeof sa;

    if( getpeername(socket, &sa, &iLen) != 0 )
        return false;

    strcpy(sBuffer, inet_ntoa(reinterpret_cast<sockaddr_in*>(&sa)->sin_addr));

    return true;
}

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  

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.