Code: Select all
#NETWORK_ERROR = -1
#NETWORK_OK = 0
;-STRUCTURES
Structure SOCKADDRIN
sin_family.w
sin_port.w
sin_addr.l
sin_zero.b[8]
EndStructure
Structure HOSTENT
h_name.l
h_aliases.l
h_addrtype.w
h_length.w
h_addr_list.l
EndStructure
;-PROTOTYPES
Declare ReportError(ErrorID.l, Source.s)
;-PROGRAM START
; Initialize Winsock
Debug "Initializing Winsock..."
WSAStartup_($0101,@wsaData.WSADATA)
; Retrieve required information about the host
Hostname.s = "www.purebasic.com"
Debug "Getting host info from: "+ Hostname +"..."
HostInfoPointer = GetHostByName_(Hostname)
If HostInfoPointer = 0
ReportError(WSAGetLastError_(),"GetHostByName()")
WSACleanup_() : End
EndIf
; Copy the data into a more pb-hospitable memory space
CopyMemory(HostInfoPointer,HostInfo.HOSTENT,SizeOf(HOSTENT))
; Retrieve the IP address
IPAddress.l = PeekL(HostInfo\h_addr_list)
Debug "Resolved IP Address: "+ StrU(PeekB(IPAddress),#BYTE)+"."+StrU(PeekB(IPAddress+1),#BYTE)+"."+StrU(PeekB(IPAddress+2),#BYTE)+"."+StrU(PeekB(IPAddress+3),#BYTE)
; Create the socket
Debug "Creating socket..."
SocketID.l = Socket_(#AF_INET,#SOCK_STREAM,#IPPROTO_TCP)
If SocketID = #INVALID_SOCKET
ReportError(WSAGetLastError_(),"socket()")
WSACleanup_() : End
EndIf
; Fill a SOCKADDRIN struct with server's address information
ServerPort = 80
ServerInfo.SOCKADDRIN
ServerInfo\sin_family = #AF_INET
ServerInfo\sin_addr = IPAddress
ServerInfo\sin_port = htons_(ServerPort)
ServerInfo\sin_zero = 0
; Connect to the server
Debug "Connecting socket on port "+ Str(ServerPort) +"..."
If Connect_(SocketID,@ServerInfo,SizeOf(SOCKADDRIN)) = #SOCKET_ERROR
ReportError(WSAGetLastError_(),"connect()")
WSACleanup_() : End
EndIf
; Successfully connected!
; This is where you send/recv data
; Close the socket, and clean up
Debug "Closing socket..."
CloseSocket_(SocketID)
Debug "Cleaning up WinSock..."
WSACleanup_()
End
Procedure ReportError(ErrorID.l, Source.s)
Debug "Call to "+ Source +" returned error "+ StrU(ErrorID,#LONG) +"!"
EndProcedure
