c / c++ and any other natively compiled language get their networking from the operating system.
this is really win, iv learnt a lot from it
http://beej.us/guide/bgnet/output/html/multipage/index.htmlalso, you should go to the IRC channel #c or #c++ on the freenode network, they can help you a lot there
this is a snippet from a small program of mine, this part gets a website with http and parses out the html,
parsing could be nicer, but oh well, if anyone knows a better way, do mention it to me.
another thing, it doesnt check the return value of send() so if not all the data it sent, it wont resend it
its written in C, so save it as MyProg.c and compile it with gcc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef __unix__
#error Must compile on unix
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
char* getFact() {
//http://modnar.byethost13.com/random.php
struct hostent* host = gethostbyname("modnar.byethost13.com");
if(host == NULL) {
herror("cant find host");
return NULL;
}
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(80);
address.sin_addr.s_addr = ((struct in_addr*)host->h_addr)->s_addr;
int sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock_fd < 0) {
perror("failed to open socket");
return NULL;
}
if(connect(sock_fd, (struct sockaddr*)&address, sizeof address) < 0) {
perror("failed to connect");
return NULL;
}
char* str = "GET /random.php HTTP/1.1\r\nHost: modnar.byethost13.com\r\nUser-Agent: Mozilla/5.0 (Linux; X11; UTF-8)\r\n\r\n";
send(sock_fd, str, strlen(str), 0);
//skip the http header
char smallBuffer[1];
int rv = 0;
int lineEndCount = 0;
while((rv = recv(sock_fd, smallBuffer, 1, 0)) > 0) {
if(smallBuffer[0] == '\r' || smallBuffer[0] == '\n') {
lineEndCount++;
if(lineEndCount == 4)
break;
} else {
lineEndCount = 0;
}
}
if(rv < 0)
perror(NULL);
//now onto the payload
char buffer[512];
rv = recv(sock_fd, buffer, 512, 0);
if(rv < 0) {
perror(NULL);
return NULL;
}
close(sock_fd);
char* first = strstr(buffer, "<td>");
char* last = strstr(buffer, "</td>");
if(first == NULL || last == NULL)
return NULL;
first += 4;
char* result = (char*)malloc(last - first);
memcpy(result, first, last - first);
result[last - first] = '\0';
return result;
}
int main(int argc, char** argv) {
//yakman
char* fact = getFact();
if(fact == NULL)
return EXIT_FAILURE;
printf("fact=%s", fact);
free(fact);
}
oh btw, the above snippet is written for unix systems (like Linux, Mac, BSD), the windows socket library (called WinSock) is almost the same,
except you have to call WSAStartup() before using it, and WSACleanup() when you finish, also you have to use closesocket() instead of close(), and you have to tell your compiler to link to the winsock library, also winsock doesnt implement raw sockets
and beej's website is fairly bias against windows too, but its still a good site for it