Jump to content
Sign in to follow this  
matwachich

Need advise on my WSA TCP functions [C]

Recommended Posts

matwachich

Hi everybody!

I wanted to learn winsockets, and for this, I try to reproduce AutoIt's TCP functions.

My code is working pretty good!

I juste want somebody, an AutoIt dev, to look my code and tell me if I'm doing something wrong, or something need to be done differently.

Another problem, is that when I close a socket on one side of a connection, the recv functions in the other side doesn't detect the close action! (like TCPRecv would return an @error)

Thanks in advance!

(I compile it with GCC 4x)

Here is the code

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#define WINVER 0x0501
#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>

#include <stdio.h>
#include <stdlib.h>

/* -------------------------------------------------------------------------- */

#define SIMPLE_TCP_BUILD_DLL
#include "simpletcp.h"

/* -------------------------------------------------------------------------- */

#define CHECK_INIT if (_global_ == NULL) return;
#define CHECK_INIT_RET(ret) if (_global_ == NULL) return ret;

#define SET_ERR(func) sprintf(_global_->err_func, "%s", func); _global_->err = WSAGetLastError();
#define UNSET_ERR sprintf(_global_->err_func, "%s", ""); _global_->err = 0;

/* -------------------------------------------------------------------------- */

typedef struct {
    WSADATA wsaData;
    char err_func[20];
    int err;
} simple_tcp_t;

simple_tcp_t* _global_ = NULL;

/* -------------------------------------------------------------------------- */
/* Standard functions */

/** \brief
 *
 * \return
 */
int     SIMPLE_TCP  TCPStartup ()
{
    if (_global_ != NULL) { return 1; }

    _global_ = malloc(sizeof(simple_tcp_t));
    if (_global_ == NULL) { return 0; }

    if (WSAStartup(MAKEWORD(2, 2), &_global_->wsaData) != 0) {
        free(_global_);
        _global_ = NULL;
        return 0;
    }

    UNSET_ERR

    return 1;
}


/** \brief
 *
 * \return
 */
void    SIMPLE_TCP  TCPShutdown ()
{
    if (_global_ == NULL) { return; }

    WSACleanup();
    free(_global_);
    _global_ = NULL;
}


/** \brief
 *
 * \param
 * \param
 *
 * \return
 */
int     SIMPLE_TCP  TCPGetError (char* err_func, const size_t err_func_len)
{
    CHECK_INIT_RET(0)
    int err = _global_->err;
    if (err_func != NULL && err_func_len > 0) {
        snprintf(err_func, err_func_len, "%s", _global_->err_func);
    }
    UNSET_ERR
    return err;
}


/** \brief
 *
 * \param
 * \param
 *
 * \return
 */
int     SIMPLE_TCP  TCPConnect (const char* host, const char* port)
{
    CHECK_INIT_RET(0)
    UNSET_ERR

    struct addrinfo hints, *result = NULL;
    ZeroMemory(&hints, sizeof(hints));

    hints.ai_family = AF_INET; // IP v4
    hints.ai_socktype = SOCK_STREAM; // Stream socket
    hints.ai_protocol = IPPROTO_TCP; // TCP

    if (getaddrinfo(host, port, &hints, &result) != 0) {
        SET_ERR("getaddrinfo")
        return 0;
    }

    SOCKET ConnectSocket = INVALID_SOCKET;
    ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ConnectSocket == INVALID_SOCKET) {
        freeaddrinfo(result);
        SET_ERR("socket")
        return 0;
    }

    if (connect(ConnectSocket, result->ai_addr, (int)result->ai_addrlen) != 0) {
        freeaddrinfo(result);
        SET_ERR("connect")
        return 0;
    }
    freeaddrinfo(result);

    unsigned long mode = 1;
    if (ioctlsocket(ConnectSocket, FIONBIO, &mode) != 0) {
        SET_ERR("ioctlsocket")
        return 0;
    }

    return ConnectSocket;
}


/** \brief
 *
 * \param
 *
 * \return
 */
int     SIMPLE_TCP  TCPListen (const char* port)
{
    CHECK_INIT_RET(0)
    UNSET_ERR

    struct addrinfo hints, *result = NULL;
    ZeroMemory(&hints, sizeof(hints));

    hints.ai_family = AF_INET; // IP v4
    hints.ai_socktype = SOCK_STREAM; // Stream socket
    hints.ai_protocol = IPPROTO_TCP; // TCP
    hints.ai_flags = AI_PASSIVE; // this + node = NULL => local host IP

    if (getaddrinfo(NULL, port, &hints, &result) != 0) {
        SET_ERR("getaddrinfo")
        return 0;
    }

    SOCKET ListenSocket = INVALID_SOCKET;
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        freeaddrinfo(result);
        SET_ERR("socket")
        return 0;
    }

    unsigned long mode = 1;
    if (ioctlsocket(ListenSocket, FIONBIO, &mode) != 0) {
        freeaddrinfo(result);
        SET_ERR("ioctlsocket")
        return 0;
    }

    if (bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen) != 0) {
        freeaddrinfo(result);
        SET_ERR("bind")
        return 0;
    }
    freeaddrinfo(result);

    if (listen(ListenSocket, SOMAXCONN) != 0) {
        SET_ERR("listen")
        return 0;
    }

    return ListenSocket;
}


/** \brief
 *
 * \param
 *
 * \return
 */
int     SIMPLE_TCP  TCPAccept (int socket)
{
    CHECK_INIT_RET(0)
    UNSET_ERR

    int err;
    SOCKET ClientSocket = INVALID_SOCKET;

    ClientSocket = accept(socket, NULL, NULL);
    err = WSAGetLastError();

    if (ClientSocket == INVALID_SOCKET && err != WSAEWOULDBLOCK) {
        SET_ERR("accept")
        return INVALID_SOCKET;
    }

    if (ClientSocket != INVALID_SOCKET) {
        unsigned long mode = 1;
        if (ioctlsocket(ClientSocket, FIONBIO, &mode) != 0) {
            SET_ERR("ioctlsocket")
            return INVALID_SOCKET;
        }
    }

    return ClientSocket;
}


/** \brief
 *
 * \param
 *
 * \return
 */
int     SIMPLE_TCP  TCPCloseSocket (int socket)
{
    CHECK_INIT_RET(0)
    UNSET_ERR

    if (shutdown(socket, SD_BOTH) != 0) {
        SET_ERR("shutdown")
        return 0;
    }

    if (closesocket(socket) != 0) {
        SET_ERR("closesocket")
        return 0;
    }

    return 1;
}


/** \brief
 *
 * \param
 * \param
 * \param
 *
 * \return
 */
int     SIMPLE_TCP  TCPSend (int socket, const char* data, const size_t data_len)
{
    CHECK_INIT_RET(0)
    UNSET_ERR

    int ret = send(socket, data, data_len, 0);
    if ((ret == SOCKET_ERROR || ret == 0) && WSAGetLastError() != WSAEWOULDBLOCK) {
        SET_ERR("send")
        return 0;
    }

    return ret;
}


/** \brief
 *
 * \param
 * \param
 * \param
 *
 * \return
 */
int     SIMPLE_TCP  TCPRecv (int socket, char* data, const size_t data_len)
{
    CHECK_INIT_RET(0)
    UNSET_ERR

    int ret = recv(socket, data, data_len, 0);
    if ((ret == 0 || ret == SOCKET_ERROR) && WSAGetLastError() != WSAEWOULDBLOCK) {
        SET_ERR("recv")
        return 0;
    }

    return ret;
}


/** \brief
 *
 * \param
 * \param
 * \param
 *
 * \return
 */
int     SIMPLE_TCP  TCPNameToIP (const char* name, char* ip, const size_t ip_len)
{
    CHECK_INIT_RET(0)
    UNSET_ERR

    struct addrinfo hints, *result = NULL;
    ZeroMemory(&hints, sizeof(hints));

    hints.ai_family = AF_INET; // IP v4
    hints.ai_socktype = SOCK_STREAM; // Stream socket
    hints.ai_protocol = IPPROTO_TCP; // TCP

    if (getaddrinfo(name, NULL, &hints, &result) != 0) {
        SET_ERR("getaddrinfo")
        return 0;
    }

    if (result->ai_family != AF_INET || result->ai_addrlen != sizeof(struct sockaddr_in)) {
        SET_ERR("bad address family")
        freeaddrinfo(result);
        return 0;
    }

    struct sockaddr_in* addr = (struct sockaddr_in*)result->ai_addr;
    char* ret = inet_ntoa(addr->sin_addr);

    snprintf(ip, ip_len, "%s", ret);
    freeaddrinfo(result);

    return 1;
}


/** \brief
 *
 * \param
 * \param
 * \param
 *
 * \return
 */
int     SIMPLE_TCP  TCPSocketToIP (int socket, char* ip, const size_t ip_len)
{
    CHECK_INIT_RET(0)
    UNSET_ERR

    struct sockaddr_in addr_in;
    int len = sizeof(addr_in);

    if (getpeername(socket, (struct sockaddr*)&addr_in, &len) != 0) {
        SET_ERR("getpeername")
        return 0;
    }

    char* ret = inet_ntoa(addr_in.sin_addr);
    if (ret == NULL) {
        SET_ERR("inet_ntoa")
        return 0;
    }

    snprintf(ip, ip_len, "%s", ret);

    return 1;
}

and the header

#ifndef __SIMPLE_TCP_H__
#define __SIMPLE_TCP_H__

#ifdef SIMPLE_TCP_BUILD_DLL
#define SIMPLE_TCP __stdcall __declspec(dllexport)
#else
#define SIMPLE_TCP __stdcall __declspec(dllimport)
#endif

/* -------------------------------------------------------------------------- */
/* Standard functions */

int     SIMPLE_TCP  TCPStartup ();
void    SIMPLE_TCP  TCPShutdown ();

int     SIMPLE_TCP  TCPGetError (char* err_func, const size_t err_func_len);

int     SIMPLE_TCP  TCPConnect (const char* ip, const char* port);
int     SIMPLE_TCP  TCPListen (const char* port);
int     SIMPLE_TCP  TCPAccept (int socket);
int     SIMPLE_TCP  TCPCloseSocket (int socket);

int     SIMPLE_TCP  TCPSend (int socket, const char* data, const size_t data_len);
int     SIMPLE_TCP  TCPRecv (int socket, char* data, const size_t data_len);

int     SIMPLE_TCP  TCPNameToIP (const char* name, char* ip, const size_t ip_len);
int     SIMPLE_TCP  TCPSocketToIP (int socket, char* ip, const size_t ip_len);

#endif // __SIMPLE_TCP_H__

Share this post


Link to post
Share on other sites
funkey

As far as I see you are just missing some timeouts.

I wrapped some C functions in AutoIt to extend the TCP functions of AutoIt.

#include "socket_UDF.au3"

_WSAStartup()

Global $iSock = _socket($AF_INET, $SOCK_STREAM, $IPPROTO_TCP)
ConsoleWrite("Socket: " & $iSock & @CRLF)

Global $tTimeVal = DllStructCreate("DWORD timeout")
DllStructSetData($tTimeVal, "timeout", 200) ; Timeout 200ms

$iSockError = _setsockopt($iSock, $SOL_SOCKET, $SO_RCVTIMEO, $tTimeVal) ; set Timeout for recv
If $iSockError Then
    ConsoleWrite("SetSockOpt error setting recv timeout!. Windows Sockets Error Codes: " & _WSAGetLastError() & @CRLF)
    _closesocket($iSock)
    TCPShutdown() ;WSACleanup
EndIf

Global $iBind = _bind($iSock, @IPAddress1, 20000) ;local IP-Address and port to use
ConsoleWrite("Bind error: " & $iBind & @CRLF) ; 0 is OK

Global $iConnect = _connect($iSock, "10.1.6.51", 80)
ConsoleWrite("Connect error: " & $iConnect & @CRLF) ; 0 is OK

If $iConnect Then
    ConsoleWrite("Windows Sockets Error Codes: " & _WSAGetLastError() & @CRLF)
    _closesocket($iSock)
    TCPShutdown() ;WSACleanup
EndIf

Global $sToSend = "GET /input1?PW=?"
Global $tSendBuffer = DllStructCreate("char[" & StringLen($sToSend) & "]")
DllStructSetData($tSendBuffer, 1, $sToSend)

Global $iSend = _send($iSock, $tSendBuffer)
ConsoleWrite("Bytes sent: " & $iSend & @CRLF)

Global $tRecvBuffer = DllStructCreate("char[64]")
Global $iRecv = _recv($iSock, $tRecvBuffer)
ConsoleWrite("Bytes received: " & $iRecv & @CRLF)

ConsoleWrite("Data received: " & DllStructGetData($tRecvBuffer, 1) & @CRLF) ;input1;OFF

_closesocket($iSock)
_WSACleanup()
 

socket_UDF.au3


Programming today is a race between software engineers striving to
build bigger and better idiot-proof programs, and the Universe
trying to produce bigger and better idiots.
So far, the Universe is winning.

Share this post


Link to post
Share on other sites
matwachich

Thanks for the answer!

Adding a timeout will not solve the problem, since my sockets are asynchronous.

I think it hase something to do with to SO_KEEPALIVE options, but I don't very well understand how it works or how to use it.

Edited by matwachich

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  

  • Similar Content

    • JuanFelipe
      By JuanFelipe
      Hello friends, I would like to know how to open a GUI from another GUI, I did it the way I leave the attached code, but when closing the second GUI they all close, they could help me to solve this problem without compiling another script. Thank you #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> $Form1 = GUICreate("Form1", 173, 126, 192, 124) $Button1 = GUICtrlCreateButton("Button1", 16, 24, 75, 25) GUISetState(@SW_SHOW) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 _form2() EndSwitch WEnd ;================================================= GUI 2 Func _form2() $Form1 = GUICreate("Form2", 615, 437, 192, 124) GUISetState(@SW_SHOW) While 2 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit EndSwitch WEnd EndFunc  
    • bowker
      By bowker
      Hi! Is there a way for me to set the value for my slider? I am getting the value for my slider with
       
      Local $strText = _UIA_getPropertyValue($oUIElement, $UIA_LegacyIAccessibleValuePropertyId) MsgBox(0,"",$strText)  
    • nacerbaaziz
      By nacerbaaziz
      Hello
      Can we pause and resume the download in the InetGet function?
      If is possible, what is the solution please?
      I used this code To manage the download

      #include <INet.au3> func _downloader($name, $linc, $filepath, $RTLF = false, $link = false) global $downloader = GUICreate("downloader", 400, 200, -1, -1, $WS_CLIPCHILDREn, $RTLF, $link) global $path = $filePath $labelTxt = GUICtrlCreateLabel("downloading " & $name, 50, 10, 200, 20) global $labelTxt0 = GUICtrlCreateLabel("downloaded size 0 MB " & "OF 0 MB", 50, 60, 300, 20) global $Progress = "" global $sText = ""     For $i = 1 To Random(5, 20, 1) ; Return an integer between 5 and 20 to determine the length of the string.         $sText &= Chr(Random(65, 122, 1)) ; Return an integer between 65 and 122 which represent the ASCII characters between a (lower-case) to Z (upper-case). next global $labelTxt2 = GUICtrlCreateInput("0%", 50, 80, 50, 20) _GUICtrlEdit_SetReadOnly(-1, true) GUIStartGroup("") global $beep = GUICtrlCreateCheckBox("use the progress beep notification", 150, 120, 200, 20) GUIStartGroup("") $button = GUICtrlCreateButton("Cancel', 130, 150, 180, 25, 0x01) $iIndex = 0 global $Target global $url GUIStartGroup("") global $Progress = GUICtrlCreateProgress(50, 90, 150, 20) global $Target = $filepath global $url = $linc global $path = $filepath global $hDownloadNo = _RSMWare_GetData($url, $Target) global $status = false AdlibRegister("SetProgress") global $onprogress = false, $curent = false GUISetState(@sw_Show) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE, $button $asc = MsgBox(4132,"exit download?","if you click yes the downloading will be cancel, do you want to cancel it ?") if $asc = 6 then AdlibUnRegister("SetProgress") GUIDelete() If $hDownloadNo <> 0 Then InetClose($hDownloadNo) exitLoop endIf EndSwitch if $status = -1 then $status = 0 $hDownloadNo = _RSMWare_GetData($url, $Target) $onprogress = false $curent = false elseIf $Status = 1 then $status = $path GUIDelete() AdlibUnRegister("SetProgress") exitLoop endIf WEnd return $status endFunc Func _RSMWare_GetData($url, $Target) Local $hDownload = InetGet($url, $Target, 1, 1) Return $hDownload EndFunc ;==>_RSMWare_GetData Func SetProgress() Local $state If $hDownloadNo <> 0 Then $state = InetGetInfo($hDownloadNo) If @error = 0 Then $infor = "downloaded size " & Round(Execute(InetGetInfo($hDownloadNo, $INET_DOWNLOADREAD) / 1048576), 2) & " MB of " & Round(Execute(InetGetInfo($hDownloadNo, $INET_DOWNLOADSIZE) / 1048576), 2) & " MB " $onprogress = Round(Ceiling(($state[0] / $state[1]) * 100)) if not (InetGetInfo($hDownloadNo, $INET_DOWNLOADSIZE) = 0) then if $onProgress <= 0 then $onProgress = 0 GUICtrlSetData($Progress, $onProgress) GUICtrlSetData($labelTxt0, $infor) GUICtrlSetData($labelTxt2, $onProgress & "%") if _isChecked($beep) then if $onprogress > $curent then beep((100 + $onprogress * 20), 100) $curent = $onprogress endIf endIf endIf If $state[2] Then If $state[3] Then InetClose($hDownloadNo) $status = 1 else InetClose($hDownloadNo) $status = -1 endIf endIf EndIf endIf EndFunc ;==>SetProgress
    • VollachR
      By VollachR
      Hi,
      I'm looking for a way to take a number value from a Row2 of a 2D array and according to this check if files that appear in rows 3-11 in the array exists.
      For example, if the number in Row2 is 5 I need to check for the files in Row 3-6 only, if it is 6 than rows 3-7 and so on.
      I thought on using a FOR loop but I have very little experience with those.
      Can you suggest the best way to do what I need?
      BTW, the files in Rows 3-11 will usually have blank value for any row above the number in Row2 (e.g. Row2 = 5 so Rows3-6 will have values but 8-11 be empty), The values I need are in Column 1 of the array, the name of the key from the INI file that the array was created from is in Column 0.
      Full Example:
      Row2 of Array:
      Col0 = Games# - Col1 = 5
      Rows3-6
      Col0 = Exe2 - Col1 = Path To File
      Col0 = Exe3 - Col1 = Path To File
      Col0 = Exe4 - Col1 = Path To File
      Col0 = Exe5 - Col1 = Path To File
      I need that if Row2 is 5 to check these above for rows if the file exists, if it was 6 then the next row as well and so on up until number 10 in Row2 as it can't go above 10.
      So basically for whatever number in Row2 from 2-10 need to check 1-9 rows from 3-11 to see if the files in Col1 exists and if any of them don't exist it should call a function that shows an error message.
      I'm pretty sure I have the first line of the for look correct:
      For $i = 1 To $aAIO[2][1] Just not sure how to continue from there, also not sure if $i should be equal 1 or 2.
      Help will be appreciated.
    • VollachR
      By VollachR
      Hi,
      I've written a specialty INI file editor for a specific set of INI files related to a bigger script I'm working on.
      I'm trying to create a verification script that checks the ini files structure and format and gives an error if they are not in expected format.
      What I did so far is create a couple of custom arrays, each with the list of Sections expected in the files and I use IniReadSectionNames in order to read the sections from the selected INI file and compare it to the array.
      It works fine, excepts it only gives an error if one or more of the sections in the custom array is missing, if they all exist but there are other additional sections that shouldn't be there it doesn't give an error and continue to open the editor screen.
      Here are the relevant part of my script:
      The Custom Verification Arrays:
      ;Creating Arrays for INI Verification Global $aSettingsVerify[7] $aSettingsVerify[1] = "Conversion" $aSettingsVerify[2] = "AIO" $aSettingsVerify[3] = "Data" $aSettingsVerify[4] = "Redist" $aSettingsVerify[5] = "Split" $aSettingsVerify[6] = "Autorun" Global $aDataVerify[6] $aDataVerify[1] = "Compression" $aDataVerify[2] = "Exclude" $aDataVerify[3] = "LangExclude" $aDataVerify[4] = "PreCommands" $aDataVerify[5] = "PostCommands" The IniReadSectionNames verification part:
      Case $OK If StringInStr($ActiveConfig, "Settings.ini") Then $CheckArray1 = IniReadSectionNames($ActiveConfig) $CheckArray2 = _ArrayCompare($aSettingsVerify, $CheckArray1) $CheckArray3 = UBound($CheckArray2, 1) If $CheckArray3 = 1 Then GUIDelete($ConfigStart) SettingsGUI() EndIf If $CheckArray3 > 1 Then WrongIni() EndIf EndIf If StringInStr($ActiveConfig, "Data") Then $CheckArray1 = IniReadSectionNames($ActiveConfig) $CheckArray2 = _ArrayCompare($aDataVerify, $CheckArray1) $CheckArray3 = UBound($CheckArray2, 1) If $CheckArray3 = 1 Then GUIDelete($ConfigStart) DataGUI() EndIf If $CheckArray3 > 1 Then WrongIni() EndIf EndIf The Function that performs the compare: (Found it in another thread on this forums somewhere by using Google Search)
      ;Compares Imported INI file with the Verification array Func _ArrayCompare(ByRef $a1, ByRef $a2) Local $nOldSize = UBound($a2) Local $a3[$nOldSize], $nNewSize = $nOldSize For $i = 0 To UBound($a1) - 1 For $j = 0 To $nOldSize - 1 If Not $a3[$j] And ($a1[$i] = $a2[$j]) Then $a3[$j] = 1 $nNewSize -= 1 EndIf Next Next Local $a4[$nNewSize], $j = 0 For $i = 0 To $nOldSize - 1 If Not $a3[$i] Then $a4[$j] = $a2[$i] $j += 1 EndIf Next Return $a4 EndFunc ;==>_ArrayCompare  
      Any way to make a check if there are sections other than the ones in the Verification Array and produce an error?
      Thanks
×