Jump to content
Che

[C++] [AJUTOR] Network connection: Ping, check online si request timeout ?

Recommended Posts

Posted

Va rog mult sa ma ajutati cu codul asta ca de dimineata, pardon, de ieri seara, imi bat capul cu el si nu reusesc sa-l fac sa mearga.

Asta este codul:


#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#include <WinSock2.h>
#include <WinInet.h>
#include <windows.h>
#include <string>
#include <stdio.h>

using std::string;

HINSTANCE hInst;
WSADATA wsaData;

void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename)
{
string::size_type n;
string url = mUrl;

if (url.substr(0, 7) == "http://")
url.erase(0, 7);

if (url.substr(0, 8) == "https://")
url.erase(0, 8);

n = url.find('/');
if (n != string::npos)
{
serverName = url.substr(0, n);
filepath = url.substr(n);
n = filepath.rfind('/');
filename = filepath.substr(n + 1);
}

else
{
serverName = url;
filepath = "/";
filename = "";
}
}

SOCKET connectToServer(char *szServerName, WORD portNum)
{
struct hostent *hp;
unsigned int addr;
struct sockaddr_in server;
SOCKET conn;

conn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (conn == INVALID_SOCKET)
return NULL;

if (inet_addr(szServerName) == INADDR_NONE)
{
hp = gethostbyname(szServerName);
}
else
{
addr = inet_addr(szServerName);
hp = gethostbyaddr((char*)&addr, sizeof(addr), AF_INET);
}

if (hp == NULL)
{
closesocket(conn);
return NULL;
}

server.sin_addr.s_addr = *((unsigned long*)hp->h_addr);
server.sin_family = AF_INET;
server.sin_port = htons(portNum);
if (connect(conn, (struct sockaddr*)&server, sizeof(server)))
{
closesocket(conn);
return NULL;
}
return conn;
}

int getHeaderLength(char *content)
{
const char *srchStr1 = "\r\n\r\n", *srchStr2 = "\n\r\n\r";
char *findPos;
int ofset = -1;

findPos = strstr(content, srchStr1);
if (findPos != NULL)
{
ofset = findPos - content;
ofset += strlen(srchStr1);
}

else
{
findPos = strstr(content, srchStr2);
if (findPos != NULL)
{
ofset = findPos - content;
ofset += strlen(srchStr2);
}
}
return ofset;
}

char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut)
{
const int bufSize = 512;
char readBuffer[bufSize], sendBuffer[bufSize], tmpBuffer[bufSize];
char *tmpResult = NULL, *result;
SOCKET conn;
string server, filepath, filename;
long totalBytesRead, thisReadSize, headerLen;

mParseUrl(szUrl, server, filepath, filename);

///////////// step 1, connect //////////////////////
conn = connectToServer((char*)server.c_str(), 80);

///////////// step 2, send GET request /////////////
sprintf_s(tmpBuffer, "GET %s HTTP/1.0", filepath.c_str());
strcpy_s(sendBuffer, tmpBuffer);
strcat_s(sendBuffer, "\r\n");
sprintf_s(tmpBuffer, "Host: %s", server.c_str());
strcat_s(sendBuffer, tmpBuffer);
strcat_s(sendBuffer, "\r\n");
strcat_s(sendBuffer, "\r\n");
send(conn, sendBuffer, strlen(sendBuffer), 0);

// SetWindowText(edit3Hwnd, sendBuffer);
printf("Buffer being sent:\n%s", sendBuffer);

///////////// step 3 - get received bytes ////////////////
// Receive until the peer closes the connection
totalBytesRead = 0;
while (1)
{
memset(readBuffer, 0, bufSize);
thisReadSize = recv(conn, readBuffer, bufSize, 0);

if (thisReadSize <= 0)
break;

tmpResult = (char*)realloc(tmpResult, thisReadSize + totalBytesRead);

memcpy(tmpResult + totalBytesRead, readBuffer, thisReadSize);
totalBytesRead += thisReadSize;
}

headerLen = getHeaderLength(tmpResult);
long contenLen = totalBytesRead - headerLen;
result = new char[contenLen + 1];
memcpy(result, tmpResult + headerLen, contenLen);
result[contenLen] = 0x0;
char *myTmp;

myTmp = new char[headerLen + 1];
strncpy(myTmp, tmpResult, headerLen);
myTmp[headerLen] = NULL;
delete(tmpResult);
*headerOut = myTmp;

bytesReturnedOut = contenLen;
closesocket(conn);
return(result);
}


int main()
{
const int bufLen = 1024;
char *szUrl = "http://www.piticigratisi.com/";
long fileSize;
char *memBuffer, *headerBuffer;
FILE *fp;

memBuffer = headerBuffer = NULL;

if (WSAStartup(0x101, &wsaData) != 0)
return -1;


memBuffer = readUrl2(szUrl, fileSize, &headerBuffer);
printf("returned from readUrl\n");
printf("data returned:\n%s", memBuffer);
if (fileSize != 0)
{
printf("Got some data\n");
fp = fopen("downloaded.file", "wb");
fwrite(memBuffer, 1, fileSize, fp);
fclose(fp);
// SetDlgItemText(hwndDlg, IDC_EDIT4, headerBuffer);
// SetDlgItemText(hwndDlg, IDC_EDIT5, memBuffer);
delete(memBuffer);
delete(headerBuffer);
}

WSACleanup();
system("PAUSE");
return 0;
}

Am cautat alte coduri sursa pe net, alte probleme asemanatoare si tot nu am reusit sa le combin sa iasa un singur program.

Cum anume va rog sa-l modificati:

1. Daca ii dai un host oarecare nu-si da seama daca hostul este online sau nu si iti da crash. Daca ii bagi un server fals cum am facut eu (piticigratisi) iti crapa.

Vreau sa poata detecta daca serverul respectiv este online sau nu si doar daca e online sa execute codul, altfel sa printeze ca serverul nu e online.

2. La fel pentru conexiune, daca s-a intrerupt cumva conexiunea sa anunte ca s-a intrerupt conexiunea.

3. Sa aiba un time request ca asa sta non stop pentru raspunsul de la server. Sa fie gen 30 de secunde si daca dupa 30 de secunde nu a primit raspuns de la server atunci sa anunte request timeout.

Atata tot.

va rog eu mult, m-am chinuit toata ziua. Nu mai pot.

Multumesc mult de tot !

Posted (edited)

ai setsockopt pentru timeout. in exemplul pe care ti l-am dat zilele trecute se vede clar ca am folosit setsockopt. sau, poti folosi non-blocking socket cu functia select.

ioctlsocket(socket, FIONBIO, 1);

ptr non-blocking socket

select:

select function (Windows)

si:


unsigned long addr;

addr = inet_addr(szServerName);
server.sin_addr.s_addr = addr;

e prost rau codul, nu stiu de unde l-ai luat :))

Edited by JIHAD
Posted
ai setsockopt pentru timeout. in exemplul pe care ti l-am dat zilele trecute se vede clar ca am folosit setsockopt. sau, poti folosi non-blocking socket cu functia select.

ioctlsocket(socket, FIONBIO, 1);

ptr non-blocking socket

select:

select function (Windows)

si:


unsigned long addr;

addr = inet_addr(szServerName);
server.sin_addr.s_addr = addr;

Si adica asta iti determina daca serverul e online sau nu ?

ioctlsocket function (Windows)

getHeaderLength e apelata cu parametru "NULL".

Nu e scris de mine codul, am vazut ca e initializat cu NULL. Dar intreb, ca nu prea ma pricep, e vreo problema sau ce vrei sa spui ? Cu ce ar trebui sa-l initializez ?

Posted (edited)

@Nytro

Am reusit si am modificat codul asa cum am vrut eu:


#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#include <WinSock2.h>
#include <WinInet.h>
#include <windows.h>
#include <string>
#include <stdio.h>

#define bzero(b,len) (memset((, '\0', (len)), (void) 0)

using std::string;

HINSTANCE hInst;
WSADATA wsaData;
int iResult;
u_long iMode = 1;

void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename)
{
string::size_type n;
string url = mUrl;

if (url.substr(0, 7) == "http://")
url.erase(0, 7);

if (url.substr(0, 8) == "https://")
url.erase(0, 8);

n = url.find('/');
if (n != string::npos)
{
serverName = url.substr(0, n);
filepath = url.substr(n);
n = filepath.rfind('/');
filename = filepath.substr(n + 1);
}

else
{
serverName = url;
filepath = "/";
filename = "";
}
}

SOCKET connectToServer(char *szServerName, WORD portNum)
{
struct hostent *hp;
unsigned int addr;
struct sockaddr_in server;
SOCKET conn;
struct timeval tv;
tv.tv_sec = 3;
tv.tv_usec = 0;
int error;

//se incearca stabilirea adresei serverului:

if (inet_addr(szServerName) == INADDR_NONE)
{
hp = gethostbyname(szServerName);
}
else
{
addr = inet_addr(szServerName);
hp = gethostbyaddr((char*)&addr, sizeof(addr), AF_INET);
}
//cream un socket:
conn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (conn == INVALID_SOCKET){
printf("Error at socket(): %ld\n", WSAGetLastError());
WSACleanup();
return NULL;
}

//mentinem socketul unblocked pentru a crea conexiuni:
iResult = ioctlsocket(conn, FIONBIO, &iMode);
if (iResult != NO_ERROR)
printf("ioctlsocket failed with error: %ld\n", iResult);

//daca adresa serverului nu este nula se incearca conexiunea:
if (hp != NULL){


//se stabilesc parametrii conexiunii:
server.sin_addr.s_addr = *((unsigned long*)hp->h_addr);
server.sin_family = AF_INET;
server.sin_port = htons(portNum);
if (server.sin_addr.s_addr != -1)
{
bzero(&(server.sin_zero), 8);
setsockopt(iResult, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
setsockopt(iResult, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
error = connect(conn, (struct sockaddr *) &server,
sizeof (struct sockaddr));
if (error == -1) return conn;
if (connect(conn, (struct sockaddr*)&server, sizeof(server))) //diferit de zero sau false => cand e bun da 1
{
wprintf(L"bind failed with error %u\n", WSAGetLastError());
closesocket(conn);
WSACleanup();
return NULL;
}
}
}

if (hp == NULL)
{
printf("Invalid IP address.\n");
closesocket(conn);
return NULL;
}




return conn;
}

int getHeaderLength(char *content)
{
const char *srchStr1 = "\r\n\r\n", *srchStr2 = "\n\r\n\r";
char *findPos;
int ofset = -1;

findPos = strstr(content, srchStr1);
if (findPos != NULL)
{
ofset = findPos - content;
ofset += strlen(srchStr1);
}

else
{
findPos = strstr(content, srchStr2);
if (findPos != NULL)
{
ofset = findPos - content;
ofset += strlen(srchStr2);
}
}
return ofset;
}

char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut)
{
const int bufSize = 512;
char readBuffer[bufSize], sendBuffer[bufSize], tmpBuffer[bufSize];
char *tmpResult=NULL, *result;
SOCKET conn;
string server, filepath, filename;
long totalBytesRead, thisReadSize, headerLen;

mParseUrl(szUrl, server, filepath, filename);

///////////// step 1, connect //////////////////////
conn = connectToServer((char*)server.c_str(), 80);
if (conn==NULL)
{
printf("Ceva nu a mers bine.\n");
return 0;
}
///////////// step 2, send GET request /////////////
sprintf_s(tmpBuffer, "GET %s HTTP/1.0", filepath.c_str());
strcpy_s(sendBuffer, tmpBuffer);
strcat_s(sendBuffer, "\r\n");
sprintf_s(tmpBuffer, "Host: %s", server.c_str());
strcat_s(sendBuffer, tmpBuffer);
strcat_s(sendBuffer, "\r\n");
strcat_s(sendBuffer, "\r\n");
send(conn, sendBuffer, strlen(sendBuffer), 0);


printf("Buffer being sent:\n%s", sendBuffer);

///////////// step 3 - get received bytes ////////////////
// Receive until the peer closes the connection
totalBytesRead = 0;
while (1)
{
memset(readBuffer, 0, bufSize);
thisReadSize = recv(conn, readBuffer, bufSize, 0);

if (thisReadSize <= 0)
break;

tmpResult = (char*)realloc(tmpResult, thisReadSize + totalBytesRead);

memcpy(tmpResult + totalBytesRead, readBuffer, thisReadSize);
totalBytesRead += thisReadSize;
}

headerLen = getHeaderLength(tmpResult);
long contenLen = totalBytesRead - headerLen;
result = new char[contenLen + 1];
memcpy(result, tmpResult + headerLen, contenLen);
result[contenLen] = 0x0;
char *myTmp;

myTmp = new char[headerLen + 1];
strncpy(myTmp, tmpResult, headerLen);
myTmp[headerLen] = NULL;
delete(tmpResult);
*headerOut = myTmp;

bytesReturnedOut = contenLen;
closesocket(conn);
return(result);
}


int main()
{
const int bufLen = 1024;
char *szUrl = "http://www.piticigratis.com/";
long fileSize;
char *memBuffer, *headerBuffer;
FILE *fp;

memBuffer = headerBuffer = NULL;

if (WSAStartup(0x101, &wsaData) != 0)
return -1;


iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR){
printf("Error at WSAStartup()\n");
return NULL;
}

memBuffer = readUrl2(szUrl, fileSize, &headerBuffer);

if (memBuffer!=NULL)
{

printf("returned from readUrl\n");
printf("data returned:\n%s", memBuffer);
if (fileSize != 0)
{
printf("Got some data\n");
fp = fopen("downloaded.file", "wb");
fwrite(memBuffer, 1, fileSize, fp);
fclose(fp);

delete(memBuffer);
delete(headerBuffer);
}
}
if (memBuffer==NULL)
{
printf("Cannot download anything !\n");
}



WSACleanup();
system("PAUSE");
return 0;
}

Se compileaza fara erori si face exact ceea ce vroiam eu sa faca. Numai ca acum a aparut o problema cat se poate de ciudata pe care nu o pot rezolva si pentru care cer ajutor:

Daca rulez executabilul asa cum e el, se deschide si da crash. Daca il rulez din compilator cu comanda "Start without debugging" tot la fel, imi da crash.

Am zis ca e musai o problema, as aca l-am luat in debugger sa vad ce are. Ciudatenia e ca in debugger nu mai crashuieste si face exact ceea ce vroiam eu sa faca. Daca il scot din debugger si il rulez ca atare imi crashuieste.

Pun si o imagine:

Capture.jpg

Iar cand il rulez ca atare, fara sa ii fac debug:

Capture.jpg

Edited by Che
Posted (edited)

setsockopt(iResult, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
setsockopt(iResult, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));

in loc de IResult trebuie sa pui conn, care este socketul tau.

daca faci socketul non-blocking nu mai folosesti setsockopt, intrucat timeoutul il setezi cu select

mai jos ti-am facut un exemplu, s-ar putea sa aiba erori, nu l-am testat.


fd_set readme;
int result, ret;
char reply[10];
struct timeval timeout;
timeout.tv_sec = 3; /* Cate secunde? */
timeout.tv_usec = 0; /* Daca nu setam aici e posibil sa avem belele. */


ioctlsocket(conn, FIONBIO, 1); /* setam non-blocking */
FD_ZERO(&readme);
FD_SET(conn, &readme);

result = connect(conn, (struct sockaddr*)(&server), sizeof(struct sockaddr_in));
if (result == -1)
{
if (errno == WSAEISCONN) /* pe win trebuie cu WSAGetLastError */
{
result = select(conn + 1, &readme, NULL, NULL, &timeout);

/* si aici if (result) daca result < 0 am esuat*/
if(result)
ret = recv(conn, reply, 10, 0); /* incercam sa vedem daca primim 10 bytes*/

/* restul e can-can, ret o sa-ti returneze numarul de bytes, daca ret <= 0 am esuat */
}


} else {
result = select(conn + 1, &readme, NULL, NULL, &timeout);

/* si aici if (result) daca result < 0 am esuat*/
if(result)
ret = recv(conn, reply, 10, 0); /* incercam sa vedem daca primim 10 bytes*/

/* restul e can-can, ret o sa-ti returneze numarul de bytes, daca ret <= 0 am esuat */

}

totodata, cand folosesti non-blocking, trebuie sa fii atent la errcode pe care ti-l returneaza conexiunea.

Pe linux este EISCONN care sugereaza succes. pe windows este WSAEISCONN. samd.

Sunt mai multe cazuri, ti-am dat doar un exemplu prin care trebuie sa faci error handling.

chiar nu am windows la indemana si te ajut din amintiri.

oricum, tinand cont de cunostintele tale cu sockets, iti recomand sa folosesti setsockopt si nu mai pune socketul in non-blocking ptr. ca nu este cazul.

Asa ca iti propun modificarile astea:

sterge astea, ti-am zis ori folosesti setsockopt ori non-blocking cu select. nu amandoua.


iResult = ioctlsocket(conn, FIONBIO, &iMode);
if (iResult != NO_ERROR)
printf("ioctlsocket failed with error: %ld\n", iResult);

aici asa trebuie:



if (server.sin_addr.s_addr != -1)
{
bzero(&(server.sin_zero), 8);
setsockopt(conn, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
setsockopt(conn, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
error = connect(conn, (struct sockaddr *) &server, sizeof (struct sockaddr));
if (error) return conn; //succes
else
{
wprintf(L"bind failed with error %u\n", WSAGetLastError());
closesocket(conn);
WSACleanup();
return NULL;
}
}

tu te conectezi de doua ori pe acelasi socket. un potential motiv pentru eroarea care-ti apare.

Edited by JIHAD
  • Upvote 1
  • Active Members
Posted

Din cate vad, nu are cum sa iti mearga codul:

Ai un:

Access violation reading location 0x00000008.

Asta inseamna ca un pointer il aloci catre o memorie la care nu ai acces.

Vezi in functia asta:


getHeaderLength(char *content)

Posted (edited)

error = connect(conn, (struct sockaddr *) &server,

sizeof (struct sockaddr));

if (error == -1) return conn;

Cred ca vrei sa zici:

error = connect(conn, (struct sockaddr *) &server,

sizeof (struct sockaddr));

if (error == -1)

{

closesocket(conn);

return NULL;

}

E urat si incalcit codul. Ia linie cu linie si incearca sa intelegei ce se intampla acolo.

Uite ce facusem eu acum mult timp...

/*
Nume: FileDownloader v0.1
Autor: Ionut Popescu
Data: 12-13 Noiembrie 2011
Descriere: Descarca un fisier de la URL-ul specificat in locatia specificata
Probleme: Nu stie de UTF-8, 404 Not Found, HTTP Location, Moved Permanently si alte lucruri
*/

#ifdef _MSC_VER
#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable: 4996)
#undef UNICODE
#endif

#define WIN32_LEAN_AND_MEAN

/* Headere necesare */

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

/* Prototipurile functiilor */

void InitWinsock();
char *GetServer(const char *url);
char *GetIP(const char *server);
char *BuildHTTPRequest(const char *url);
int DownloadFile(const char *url, const char *filename);

/* Functia descarca un fisier de la adresa specificata */

int DownloadFile(const char *url, const char *file_name)
{
char *request = NULL, *server = NULL, *server_ip = NULL, recv_buffer[4096];
SOCKET sock;
struct sockaddr_in conn;
int eroare_connect = -1, rez_send = -1, rez_recv = -1, bytes = 0, first_packet = 1;
HANDLE hFisier = NULL;
DWORD written;

/* Cream request-ul, si memoram IP-ul serverului */

request = BuildHTTPRequest(url);
server = GetServer(url);
server_ip = GetIP(server);

sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

/* Verificam crearea socketului */

if(sock == INVALID_SOCKET)
{
puts("Eroare, nu s-a putut crea socketul");
if(WSAGetLastError() == WSAENETDOWN) puts("- Problema cu conexiunea la internet");

exit(EXIT_FAILURE);
}

/* Facem "setarile" necesare si ne conectam la server */

conn.sin_family = AF_INET;
conn.sin_port = htons(80);
conn.sin_addr.s_addr = inet_addr(server_ip);

eroare_connect = connect(sock, (struct sockaddr *)&conn, sizeof(conn));

/* Verificam daca s-a realizat conexiunea */

if(eroare_connect == SOCKET_ERROR)
{
puts("Eroare la conectarea la server");
eroare_connect = WSAGetLastError();

switch(eroare_connect)
{
case WSAENETDOWN:
puts("- Problema cu conexiunea la internet");
break;
case WSAEADDRNOTAVAIL:
puts("- Adresa nu este valida");
break;
case WSAECONNREFUSED:
puts("- Conexiunea a fost refuzata");
break;
case WSAENETUNREACH:
puts("- Nu s-a putut realiza conexiunea la retea");
break;
case WSAEHOSTUNREACH:
puts("- Nu s-a putut realiza conexiunea la server");
break;
case WSAETIMEDOUT:
puts("- Conexiunea a esuat dupa timpul limita");
break;
default:
printf("- A intervenit eroarea cu codul: %d\n", eroare_connect);
}

closesocket(sock);
exit(EXIT_FAILURE);
}

/* Trimitem request-ul */

rez_send = send(sock, request, strlen(request), 0);

if(rez_send == SOCKET_ERROR)
{
puts("Eroare la trimiterea request-ului");

rez_send = WSAGetLastError();

switch(rez_send)
{
case WSAENETDOWN:
puts("- Problema cu conexiunea la internet");
break;
case WSAECONNABORTED:
puts("- Conexiunea a fost terminata dupa timpul limita");
break;
case WSAECONNRESET:
puts("- Conexiunea a fost resetata de server");
break;
case WSAETIMEDOUT:
puts("- Conexiune inchisa din cauza retelei sau serverului respectiv");
break;
default:
printf("- A intervenit eroarea cu codul: %d\n", rez_send);
}
}

/* Nu mai trimitem date */

shutdown(sock, SD_SEND);

/* Citim raspunsul de la server */

do
{
bytes = recv(sock, recv_buffer, 4096, 0);

if(bytes > 0)
{
/* Daca e primul pachet, separam datele de headerele HTTP */

if(first_packet == 1)
{
char delim[5] = {0};
int pos_buf = 0;

/* Prevenim eventuale probleme */

if(strlen(recv_buffer) < 4) continue;

sprintf(delim, "\r\n\r\n");

while(pos_buf < 1024 && recv_buffer[pos_buf+4] && (strncmp(&recv_buffer[pos_buf], delim, 4) != 0)) pos_buf++;

/* Scriem in fisier */

hFisier = CreateFile(file_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

if(hFisier != INVALID_HANDLE_VALUE)
{
WriteFile(hFisier, &recv_buffer[pos_buf + 4], bytes - pos_buf - 4, &written, NULL);
}
else
{
puts("Eroare, nu s-a poate crea fisierul");
break;
}

first_packet = 0;
}
else WriteFile(hFisier, recv_buffer, bytes, &written, NULL);
}
else if(bytes == 0)
{
puts("Fisierul a fost descarcat cu succes!");

CloseHandle(hFisier);
}

/* Eroare la citirea datelor */

else
{
puts("Eroare la citirea datelor de la server");

rez_recv = WSAGetLastError();

switch(rez_recv)
{
case WSAENETDOWN:
puts("- Problema cu conexiunea la internet");
break;
case WSAECONNABORTED:
puts("- Conexiunea a fost terminata dupa timpul limita");
break;
case WSAECONNRESET:
puts("- Conexiunea a fost resetata de server");
break;
case WSAETIMEDOUT:
puts("- Conexiune inchisa din cauza retelei sau serverului respectiv");
break;
default:
printf("- A intervenit eroarea cu codul: %d\n", eroare_connect);
}
}

} while(bytes > 0);

closesocket(sock);

return 1;
}

/* Functia returneaza IP-ul unui server */

char* GetIP(const char *server)
{
struct hostent *host;
struct in_addr address;

host = gethostbyname(server);

/* Verificam rezultatul */

if(host == NULL)
{
int eroare_ip = -1;

puts("A intervenit o eroare la preluarea IP-ului serverului");

switch(eroare_ip = WSAGetLastError())
{
case WSAHOST_NOT_FOUND:
puts("- Serverul nu a fost gasit");
break;
case WSANO_DATA:
puts("- Nu a fost gasit niciun IP pentru server");
break;
default:
printf("- A intervenit eroarea cu codul: %d\n", eroare_ip);
}

exit(EXIT_FAILURE);
}

/* Verificare si conversie */

if(host->h_addr_list[0] == 0)
{
puts("Eroare, nu s-a gasit niciun IP pentru server");
exit(EXIT_FAILURE);
}

/* Convertim reprezentarea*/

address.s_addr = *(u_long*)host->h_addr_list[0];
/* address = *(struct in_addr*)(host->h_addr_list[0]); */

/* Convertim adresa la sir de caractere si o returnam */

return inet_ntoa(address);
}

/* Functia construieste headerele HTTP necesare, memoram serverul in al doilea parametru */

char *BuildHTTPRequest(const char *url)
{
const char browser[] = "Mozilla/5.0 (Windows NT 6.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1";
char *request = NULL, *local_url = NULL, *host = NULL;
char fileurl[1024];

/* Prevenim buffer oveflow */

if(strlen(url) > 1024) return NULL;

host = GetServer(url);
local_url = (char *)malloc(1024);

/* Extragem si numele fisierului */

if(strncmp(url, "http://", 7) == 0) strcpy(local_url, url +7);
else strcpy(local_url, url);

strcpy(fileurl, local_url + strlen(host));

/* Alocam spatiu si cream headerul */

request = (char *)malloc(4096);
sprintf(request, "GET %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: %s\r\n\r\n", fileurl, host, browser);

return request;
}

/* Functia returneaza serverul dintr-un URL */

char *GetServer(const char *url)
{
char *local_url = NULL, *host = NULL;
int i = 0;

/* Prevenim buffer oveflow */

if(strlen(url) >= 1024) return NULL;

/* Extragem datele necesare pentru a crea headerul */

local_url = (char *)malloc(1024);

if(strncmp(url, "http://", 7) == 0) strcpy(local_url, url +7);
else strcpy(local_url, url);

/* Copiem serverul in variabila host */

host = (char *)malloc(1024);

while(local_url[i] && local_url[i] != '/')
{
host[i] = local_url[i];
i++;
}
host[i] = '\0';

return host;
}

/* Alocam resursele Winsock si verificam pentru potentiale erori */

void InitWinsock()
{
WSADATA wsaData;

/* Initializare Winsock */

if(WSAStartup(MAKEWORD(2,2), &wsaData))
{
int eroare_wsa = -1;
puts("A intervenit o eroare la initializarea Winsock:");

switch(eroare_wsa = WSAGetLastError())
{
case WSASYSNOTREADY:
puts("- Problema cu conexiunea la Internet");
break;
case WSAEPROCLIM :
puts("- Problema cu resursele alocate de sistemul de operare");
break;
default:
printf("- A intervenit eroarea cu codul: %d\n\n", eroare_wsa);
}

exit(EXIT_FAILURE);
}
}

/* Main-ul clasic */

int main()
{
char x;

InitWinsock();
DownloadFile("http://www.digitalxx.ro/lista.txt", "Test.txt");
WSACleanup();

scanf("%c", &x);
return 0;
}

Edited by Nytro

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...