(?) Работа с сокетами

Раздел посвящен программированию с использованием Power Basic.
SLUTER
Новичок
Новичок
 
Сообщения: 49
Зарегистрирован: 06.06.2010 (Вс) 18:26

(?) Работа с сокетами

Сообщение SLUTER » 10.04.2011 (Вс) 15:25

Пытаюсь портировать с VB6, но ничего не получается.
Нужно отправить GET запрос гуглу и получить ответ.

Направьте в правильное русло.

код ниже.
Код: Выделить всё
#COMPILE EXE
#DIM ALL

#INCLUDE ONCE "Win32API.inc"

%INVALID_SOCKET = &HFFFFFFFF???

%AF_INET            = 2
%IPPROTO_TCP        = 6
%SOCK_STREAM        = 1
%WSADESCRIPTION_LEN = 256
%WSASYS_STATUS_LEN  = 128

UNION in_addr
  s_addr AS LONG
  s AS STRING * 4
END UNION

TYPE WSADATA
  wVersion AS WORD
  wHighVersion AS WORD
  szDescription AS ASCIIZ * %WSADESCRIPTION_LEN + 1
  xFiller1 AS STRING * 3
  szSystemStatus AS ASCIIZ * %WSASYS_STATUS_LEN + 1
  xFiller2 AS STRING * 3
  iMaxSockets AS WORD
  iMaxUdpDg AS WORD
  lpVendorInfo AS ASCIIZ PTR
END TYPE

TYPE HOSTENT
  h_name AS ASCIIZ PTR
  h_aliases AS ASCIIZ PTR
  h_addrtype AS INTEGER
  h_length AS INTEGER
  h_addr_list AS DWORD PTR
END TYPE

TYPE SOCKADDR_IN
  sin_family AS INTEGER
  sin_port AS WORD
  sin_addr AS LONG
  sin_zero AS STRING * 8
END TYPE


DECLARE FUNCTION WSAStartup LIB "ws2_32.dll" ALIAS "WSAStartup" (BYVAL wVR AS WORD, lpWSAD AS WSADATA) AS LONG
DECLARE FUNCTION WSACleanup LIB "ws2_32.dll" ALIAS "WSACleanup" () AS LONG
DECLARE FUNCTION cconnect LIB "ws2_32.dll" ALIAS "connect" (BYVAL s AS DWORD, sname AS sockaddr_in, BYVAL namelen AS LONG) AS LONG
DECLARE FUNCTION socket LIB "ws2_32.dll" ALIAS "socket" (BYVAL af AS LONG, BYVAL s_type AS LONG, BYVAL protocol AS LONG) AS DWORD
DECLARE FUNCTION gethostbyname LIB "ws2_32.dll" ALIAS "gethostbyname" (hname AS ASCIIZ) AS DWORD
DECLARE FUNCTION ssend LIB "ws2_32.dll" ALIAS "send" (BYVAL s AS DWORD, buf AS ANY, BYVAL buflen AS LONG, BYVAL flags AS LONG) AS LONG
DECLARE FUNCTION rrecv LIB "ws2_32.dll" ALIAS "recv" (BYVAL s AS DWORD, buf AS ANY, BYVAL buflen AS LONG, BYVAL flags AS LONG) AS LONG
DECLARE FUNCTION closesocket LIB "ws2_32.dll" ALIAS "closesocket" (BYVAL s AS DWORD) AS LONG

DECLARE FUNCTION htons LIB "ws2_32.dll" ALIAS "htons" (BYVAL hostshort AS WORD) AS WORD
DECLARE FUNCTION inet_addr LIB "ws2_32.dll" ALIAS "inet_addr" (cp AS ASCIIZ) AS DWORD

GLOBAL SocketAddress AS sockaddr_in


FUNCTION SocketInit() AS LONG
    DIM wsastruct AS WSADATA
    IF WSAStartup(&H101, wsastruct) = 0 THEN
        FUNCTION = 1
    ELSE
        FUNCTION = 0
    END IF
END FUNCTION

FUNCTION SocketCleanup() AS LONG
    IF WSACleanup = 0 THEN
        SocketCleanup = 1
    ELSE
        SocketCleanup = 0
    END IF
END FUNCTION


FUNCTION SendData(BYVAL s AS DWORD, vMessage AS STRING) AS LONG
    DIM TheMsg() AS BYTE, sTemp$
    'Select Case variant#(vMessage)
    '    Case 8209   'byte array
    '        sTemp = vMessage
    '        TheMsg() = sTemp
    '    Case 8      'string, if we recieve a string, its assumed we are linemode
    '        sTemp = vMessage'StrConv(vMessage, vbFromUnicode)
    '    Case Else
    '        sTemp = CStr(vMessage)
    '        sTemp = vMessage'StrConv(vMessage, vbFromUnicode)
    'End Select
    'TheMsg() = sTemp
    'If UBound(TheMsg) > -1 Then
    '    SendData = ssend(s, TheMsg(0), (UBound(TheMsg) - LBound(TheMsg) + 1), 0)
    'End If
    SendData = ssend(s, vMessage, LEN(vMessage), 0)
END FUNCTION



FUNCTION PBMAIN () AS LONG
    LOCAL sock,result AS LONG
    LOCAL query AS STRING
    LOCAL clen, clen2 AS LONG

    SocketCleanup

    IF SocketInit = 0 THEN MSGBOX "ERROR 1": EXIT FUNCTION
    IF AntiCaptchaInit = 0 THEN MSGBOX "ERROR 2": EXIT FUNCTION

    sock = socket(2, 1, 6)
    'sock = socket(%AF_INET, %SOCK_STREAM, 0)

    IF sock = %INVALID_SOCKET OR sock = -1 THEN MSGBOX "ERROR 3": EXIT FUNCTION

    IF cconnect(sock, SocketAddress, LEN(SocketAddress)) <> 0 THEN MSGBOX "ERROR 4": EXIT FUNCTION


    query = "GET / HTTP/1.1" + $CRLF
    query = query + "Accept: */*" + $CRLF
    query = query + "Content-Type: application/x-www-form-urlencoded" + $CRLF
    query = query + "Accept-Language: ru" + $CRLF
    query = query + "User-Agent: Opera" + $CRLF
    query = query + "Host: google.com" + $CRLF
    query = query + "Connection: Keep-Alive" + $CRLF + $CRLF

    clen = LEN(query)
    clen2 = SendData(sock, query)

    IF clen2 <> clen THEN
        closesocket sock
        MSGBOX "ERROR 5"
        EXIT FUNCTION
    END IF


    'LOCAL buf AS STRING
    'rrecv(sock, buf, 256, 0)
    'closesocket sock
    'msgbox buf
END FUNCTION


FUNCTION AntiCaptchaInit() AS LONG
    DIM hostinfo AS HOSTENT
    DIM pHostinfo AS LONG
    DIM pIPAddress AS LONG
    DIM ipAddress AS LONG

    pHostinfo = gethostbyname("google.com")
    IF pHostinfo = 0 THEN
        wsacleanup
        FUNCTION = 0
        EXIT FUNCTION
    END IF

    MoveMemory hostinfo, BYVAL pHostinfo, LEN(hostinfo)
    IF hostinfo.h_addrtype <> %AF_INET THEN
        wsacleanup
        FUNCTION = 0
        EXIT FUNCTION
    END IF

    MoveMemory pIPAddress, BYVAL hostinfo.h_addr_list, 4
    MoveMemory ipAddress, BYVAL pIPAddress, 4

    SocketAddress.sin_addr = ipAddress
    SocketAddress.sin_port = htons(80)'&H5000
    SocketAddress.sin_family = %AF_INET

    FUNCTION = 1
END FUNCTION

Хакер
Телепат
Телепат
Аватара пользователя
 
Сообщения: 16478
Зарегистрирован: 13.11.2005 (Вс) 2:43
Откуда: Казахстан, Петропавловск

Re: (?) Работа с сокетами

Сообщение Хакер » 10.04.2011 (Вс) 19:15

Почему бы не использовать WinHTTP?
—We separate their smiling faces from the rest of their body, Captain.
—That's right! We decapitate them.

SLUTER
Новичок
Новичок
 
Сообщения: 49
Зарегистрирован: 06.06.2010 (Вс) 18:26

Re: (?) Работа с сокетами

Сообщение SLUTER » 10.04.2011 (Вс) 22:41

Хакер писал(а):Почему бы не использовать WinHTTP?

как я понял WinHTTP берёт на себя всю работу по обработке ответов, что не всегда уместно и нужно.

да и просто хочется попробовать вот так.

Хакер
Телепат
Телепат
Аватара пользователя
 
Сообщения: 16478
Зарегистрирован: 13.11.2005 (Вс) 2:43
Откуда: Казахстан, Петропавловск

Re: (?) Работа с сокетами

Сообщение Хакер » 11.04.2011 (Пн) 10:47

SLUTER писал(а):как я понял WinHTTP берёт на себя всю работу по обработке ответов, что не всегда уместно и нужно.

Какую именно работу по обработке ответов нужно производить самому?
—We separate their smiling faces from the rest of their body, Captain.
—That's right! We decapitate them.

SLUTER
Новичок
Новичок
 
Сообщения: 49
Зарегистрирован: 06.06.2010 (Вс) 18:26

Re: (?) Работа с сокетами

Сообщение SLUTER » 13.04.2011 (Ср) 13:37

например перенаправления.
так же не устраивает, что принятые кукисы потом используются в иэксплорере.

да и вообще суть не в этом, просто хочу понять, почему код выше не работает.

SLUTER
Новичок
Новичок
 
Сообщения: 49
Зарегистрирован: 06.06.2010 (Вс) 18:26

Re: (?) Работа с сокетами

Сообщение SLUTER » 03.05.2011 (Вт) 16:21

как-то поднатужился и корявенько перевёл пример с с++
работает :D

подскажите, может что не так или через задницу. спасибо.
Код: Выделить всё
#COMPILE EXE

%INVALID_SOCKET = &HFFFFFFFF???
%SOCKET_ERROR   = -1

%WSADESCRIPTION_LEN = 256
%WSASYS_STATUS_LEN  = 128

%AF_INET      = 2
%PF_INET      = %AF_INET

%SOCK_STREAM  = 1

TYPE WSADATA
  wVersion AS WORD
  wHighVersion AS WORD
  szDescription AS ASCIIZ * %WSADESCRIPTION_LEN + 1
  xFiller1 AS STRING * 3
  szSystemStatus AS ASCIIZ * %WSASYS_STATUS_LEN + 1
  xFiller2 AS STRING * 3
  iMaxSockets AS WORD
  iMaxUdpDg AS WORD
  lpVendorInfo AS ASCIIZ PTR
END TYPE

TYPE HOSTENT
  h_name AS ASCIIZ PTR
  h_aliases AS ASCIIZ PTR
  h_addrtype AS INTEGER
  h_length AS INTEGER
  h_addr_list AS DWORD PTR
END TYPE

TYPE SOCKADDR_IN
  sin_family AS INTEGER
  sin_port AS WORD
  sin_addr AS LONG
  sin_zero AS STRING * 8
END TYPE

DECLARE SUB MoveMemory LIB "KERNEL32.DLL" ALIAS "RtlMoveMemory" (pDestination AS ANY, pSource AS ANY, BYVAL cbLength AS LONG)

DECLARE FUNCTION WSAStartup LIB "ws2_32.dll" ALIAS "WSAStartup" (BYVAL wVR AS WORD, lpWSAD AS WSADATA) AS LONG
DECLARE FUNCTION socket LIB "ws2_32.dll" ALIAS "socket" (BYVAL af AS LONG, BYVAL s_type AS LONG, BYVAL protocol AS LONG) AS DWORD
DECLARE FUNCTION gethostbyname LIB "ws2_32.dll" ALIAS "gethostbyname" (hname AS ASCIIZ) AS DWORD
DECLARE FUNCTION htons LIB "ws2_32.dll" ALIAS "htons" (BYVAL hostshort AS WORD) AS WORD
DECLARE FUNCTION cconnect LIB "ws2_32.dll" ALIAS "connect" (BYVAL s AS DWORD, sname AS sockaddr_in, BYVAL namelen AS LONG) AS LONG
DECLARE FUNCTION ssend LIB "ws2_32.dll" ALIAS "send" (BYVAL s AS DWORD, buf AS ANY, BYVAL buflen AS LONG, BYVAL flags AS LONG) AS LONG
DECLARE FUNCTION rrecv LIB "ws2_32.dll" ALIAS "recv" (BYVAL s AS DWORD, buf AS ANY, BYVAL buflen AS LONG, BYVAL flags AS LONG) AS LONG
DECLARE FUNCTION closesocket LIB "ws2_32.dll" ALIAS "closesocket" (BYVAL s AS DWORD) AS LONG

FUNCTION PBMAIN () AS LONG
    LOCAL TWSAData AS WSADATA
    LOCAL FHosten AS HOSTENT
    LOCAL FAddr AS sockaddr_in
    LOCAL FSocket AS LONG
    LOCAL HostName AS LONG
    LOCAL ipAddress AS LONG
    LOCAL pIPAddress AS LONG

    LOCAL request AS STRING

    IF WSAStartup(&H101, TWSAData) <> 0 THEN MSGBOX "ERR 1": EXIT FUNCTION

    FSocket = socket(%PF_INET, %SOCK_STREAM, 0)
    IF FSocket = %INVALID_SOCKET THEN MSGBOX "ERR 2": EXIT FUNCTION

    HostName = gethostbyname("www.google.com")
    MoveMemory FHosten, BYVAL HostName, LEN(FHosten)

    IF FHosten.h_addrtype <> %AF_INET THEN MSGBOX "ERR 3": EXIT FUNCTION

    MoveMemory pIPAddress, BYVAL FHosten.h_addr_list, 4
    MoveMemory ipAddress, BYVAL pIPAddress, 4

    FAddr.sin_family = %PF_INET
    FAddr.sin_addr = ipAddress
    FAddr.sin_port = htons(80)

    IF cconnect(FSocket, FAddr, LEN(FAddr)) <> 0 THEN MSGBOX "ERR 4": EXIT FUNCTION

    request = "GET / HTTP/1.1" + $CRLF
    request = request + "User-Agent: Opera/9.80" + $CRLF
    request = request + "Host: www.google.com" + $CRLF
    request = request + "Accept: text/html" + $CRLF
    request = request + "Connection: Keep-Alive" + $CRLF + $CRLF

    LOCAL temp AS ASCIIZ * 260
    LOCAL buf AS STRING
    IF ssend(FSocket, BYVAL STRPTR(request), LEN(request), 0) = %SOCKET_ERROR THEN MSGBOX "ERR 5": EXIT FUNCTION

    DO
        rrecv(FSocket, temp, SIZEOF(temp), 0)
        buf = buf + temp
    LOOP UNTIL temp = "" OR ISTRUE EOF(FSocket)

    closesocket FSocket

    MSGBOX buf
END FUNCTION


Вернуться в Power Basic

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 55

    TopList