VieVa!

Plots gaat het snel: http en C

Ok, ik wil een integratie maken met dropbox. Voor zover ik kan zien is dat voor Linux enkel mogelijk met de http support.

Dus eerst maar eens een connectie met internet maken. Code van internet geplukt en werkt ! Op linux met GCC compiler.

maarten@maarten-K53TK ~/Documenten $ gcc connectohttp.c
maarten@maarten-K53TK ~/Documenten $ ./a.out http://www.google.com
HTTP/1.1 200 OK
Date: Sun, 30 Dec 2018 18:39:07 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
P3P: CP=”This is not a P3P policy! See g.co/p3phelp for more info.”
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Set-Cookie: 1P_JAR=2018-12-30-18; expires=Tue, 29-Jan-2019 18:39:07 GMT; path=/; domain=.google.com
Set-Cookie: NID=152=GvccaWpv4u4MaKFwR6S8S92EgZII3FyzXVLrJscbAru3c20-WKv-Ij7QRWOmztcFseNxpzWSHx2jgxdZwHRPQUDLoIXx-qDcjdTFHYmV3Yzf1Lq5xs6cUzNymRgyS7–D77E5ZftRSoOvCHsAdylKDfBD5ivQWGgBcaBFZ1h0K4; expires=Mon, 01-Jul-2019 18:39:07 GMT; path=/; domain=.google.com; HttpOnly
Accept-Ranges: none
Vary: Accept-Encoding
Connection: close

Google<script nonce="n7rApHEitx
maarten@maarten-K53TK ~/Documenten $ ./a.out ietsanders
Can't find host ietsanders. Program terminating…
maarten@maarten-K53TK ~/Documenten $

Volledige code:
#include &ltnetdb.h>
#include &lt
#include &ltstdlib.h>
#include &ltstring.h>
#include &ltsys/types.h>
#include &ltsys/socket.h>
#include &ltnetinet/in.h>

int main(int argc, char *argv[])
{
FILE *fout;

int i, c, sk;
char *tk, host[64], path[64], fname[64], http_msg[256], buf[1024];
struct sockaddr_in remote;
struct hostent *hp;
struct servent *se;

if(argc != 2)
{
printf("Invalid number of arguments. Program terminating...\n");
exit(1);
}
bzero(&remote, sizeof(remote));
sk = socket(AF_INET, SOCK_STREAM, 0);
remote.sin_family = AF_INET;
c = 0;
tk = strtok(argv[1], "/");
while(tk != NULL)
{
if(c == 0)
strcpy(host, tk);
else if(c == 1)
strcpy(path, tk);
else
strcpy(fname, tk);
++c;
tk = strtok(NULL, "/");
}
snprintf(http_msg, 256, "GET /%s/%s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\n", path, fname, host);
hp = gethostbyname(host);
if(hp == NULL)
{
printf("Can't find host %s. Program terminating...\n", host);
exit(1);
}
se = getservbyname("http", "tcp");
remote.sin_port = se->s_port;
bcopy((char *)hp->h_addr, (char *)&remote.sin_addr.s_addr, hp->h_length);

if(connect(sk, (struct sockaddr*)&remote, sizeof(remote)) < 0)
{
printf("Connection attempt failed. Program terminating...\n");
exit(1);
}
send(sk, http_msg, sizeof(http_msg) + 1, 0);
recv(sk, buf, sizeof(buf), 0);
printf("%s\n", buf);
return 0;
}

Leave a comment

Blog at WordPress.com.